Thursday, April 10, 2014

Using SSH.NET Getting a list of files from ftp server

  1. First download SSH.NET library
    • From VS 2013, right click "Reference" and select "Manage NuGet Packages..."
    • Search for "SSH" and you'll see "SSH.NET" as an option.  
    • Click "Install" and it will add a reference called "Renci.Ssh.Net"
  2. In your .proj, add a class file.
  3. Sample code:
    public class FtpHelper
    {
    public FtpHelper() { }

    public void GetFile(string host, string username, string password)
    {

    SftpClient sftpClient = new SftpClient(host, username, password);
    sftpClient.Connect();
    List<SftpFile> fileList = sftpClient.ListDirectory("/outgoing/test").ToList();

    if (fileList != null && fileList.Count() > 2)
    {
    for (int i = 2; i < fileList.Count(); i++)
    {
    string destinationFile = "C:\\" + fileList[i].Name;
    using (var stream = new FileStream(destinationFile, FileMode.Create))
    {
    sftpClient.DownloadFile(fileList[i].FullName, stream);
    stream.Close();
    }
    }
    }
    sftpClient.Disconnect();
    }
  4. Unit Test
            [TestMethod]
            public void GetFileTest_JHGA_PickUpTestSite_ReturnNoError()
            {
                FtpHelper ftp = new FtpHelper();
                ftp.GetFile("ftp.yoursite.com", "yourusername", "yourPassword");
             
            }
  5. Done!

Using SSH.NET Getting a list of files from ftp server

First download SSH.NET library From VS 2013, right click "Reference" and select "Manage NuGet Packages..." Search fo...