I have one console app which will be scheduled as job in AZURE web site. From that console app I want to connect remote SFTP and get all files and save them in my folder ins
First of all best and free option to use in this case is WinSCP .NET assembly.
You can download it from here
So lets start this is the function:
public static void GetSftp(string host, string user, string password, int port, string source, string dest, string remoteDest)
{
Directory.CreateDirectory(dest);
var winScpSessionOptions = new SessionOptions
{
HostName = host,
Password = password,
PortNumber = port,
UserName = user,
Protocol = Protocol.Sftp,
GiveUpSecurityAndAcceptAnySshHostKey = true
};
var session = new Session();
session.Open(winScpSessionOptions);
var remoteDirInfo = session.ListDirectory(remoteDest);
foreach (RemoteFileInfo fileInfo in remoteDirInfo.Files)
{
if (fileInfo.Name.Equals(".") || fileInfo.Name.Equals("..")) { continue; }
Console.WriteLine("{0}", remoteDest + fileInfo.Name);
try
{
var x = remoteDest +"/"+ fileInfo.Name;
var y = dest +"\\"+ fileInfo.Name;
var result = session.GetFiles(x, y);
if (!result.IsSuccess)
{
}
else
{
session.RemoveFiles(remoteDest +"/"+ fileInfo.Name);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
What this function does? It just gets SFTP credentials and login to SFTP .And lists all file names .And saves each file in AZURE web site ftp.After it removes transferred file.