October 7, 2024

Download, Upload files from SFTP Server in C#

SFTP is a secured file transfer protocol. We can use it in different ways. Lot of third party tools (FileZilla,WinSCP,FireFTP etc) are available for that.  Some time we need to perform basic SFTP operation in C#. This article describes step by step Download, Upload from SFTP in C#. Summary of the article:

  • What is SFTP?
  • SFTP Operations in .NET Framework
  • File List of SFTP Server in C#
  • Download File from the SFTP Server in C#
  • Upload File from Local Machine to SFTP Server in C#

What is SFTP?
The SFTP (Secure File Transfer Protocol) or SSH File Transfer Protocol or Secure FTP is a computing network protocol for accessing and managing files on remote computer/server/file systems. Like SCP protocol SFTP also allows file transfers between hosts. Unlike standard File Transfer Protocol (FTP), SFTP encrypt both commands and data. It prevents passwords and sensitive information from being transmitted in the clear over a network.
SFTP clients are programs that use SSH to access, transfer, and manage files. It is functionally similar to FTP clients but used different protocols. Generally we cannot use standard FTP clients to connect to SFTP servers, nor can we use clients that support only SFTP to connect to FTP servers. Some Graphical clients are available for SFTP. We can also use it from the command line on a UNIX or Mac OS X computer.

SFTP Operations in .NET Framework
At present .NET Framework does not support SFTP natively. We need to use a third party or open source component to do this. Some components are

  • SharpSSH is open source and a pure .NET implementation of the SSH2 client protocol suite. It provides an API for communication with SSH servers and can be integrated into any .NET application.
  • Granados is also an SSH client library for .NET.
  • Rebex SFTP is a versatile file-transfer component for .NET languages (such as C# or VB.NET) that provides secure file system access over an SSH channel using the SFTP protocol.

This article describes how to use SharpSSH in C#. SharpSSH is a free component. For this at first we need to include Tamir.SharpSSH.dll in our project. Tamir.SharpSSH dll is available in internet. We can easily download it form the web. We need to include the following namespace in the Class.

using System.Collections;
using System.Threading;
using System.IO;
using Tamir.SharpSsh;
using Tamir.Streams;

File List of the SFTP Server in C#
The following C# code will return the list of all the file names of a SFTP Server in an Array List.

string _ftpURL = "testsftp.com"; //Host URL or address of the SFTP server
string _UserName = "admin";     //User Name of the SFTP server
string _Password = "admin123";  //Password of the SFTP server
int _Port = 22;                 //Port No of the SFTP server (if any)
string _ftpDirectory = "Receipts"; //The directory in SFTP server where the files are present
Sftp oSftp = new Sftp(_ftpURL, _UserName, _Password);
oSftp.Connect(_Port);
ArrayList FileList = oSftp.GetFileList(_ftpDirectory);
oSftp.Close();

Download File from the SFTP Server in C#
The following C# code will download all the files from the SFTP server into local machine. Remember that this code can only transfer files not folder.

string _ftpURL = "testsftp.com"; //Host URL or address of the SFTP server
string _UserName = "admin";     //User Name of the SFTP server
string _Password = "admin123";  //Password of the SFTP server
int _Port = 22;                 //Port No of the SFTP server (if any)
string _ftpDirectory = "Receipts"; //The directory in SFTP server where the files are present
string LocalDirectory = "D:\\FilePuller"; //Local directory where the files will be downloaded

Sftp oSftp = new Sftp(_ftpURL, _UserName, _Password);
oSftp.Connect(_Port);
ArrayList FileList = oSftp.GetFileList(_ftpDirectory);
FileList.Remove(".");
FileList.Remove("..");          //Remove . from the file list
FileList.Remove("Processed");   //Remove folder name from the file list. If there is no folder name remove the code.

for (int i = 0; i < FileList.Count; i++)
{
    if (!File.Exists(LocalDirectory + "/" + FileList[i]))
    {
        oSftp.Get(_ftpDirectory + "/" + FileList[i], LocalDirectory + "/" + FileList[i]);
        Thread.Sleep(100);
    }
}
oSftp.Close();

Upload File from Local Machine to SFTP Server in C#
The following C# code will upload a file from local machine to SFTP server.

string _ftpURL = "testsftp.com"; //Host URL or address of the SFTP server
string _UserName = "admin";      //User Name of the SFTP server
string _Password = "admin123";   //Password of the SFTP server
int _Port = 22;                  //Port No of the SFTP server (if any)
string _ftpDirectory = "Receipts"; //The directory in SFTP server where the files will be uploaded
string LocalDirectory = "D:\\FilePuller"; //Local directory from where the files will be uploaded
string FileName = "test.txt";    //File name, which one will be uploaded

Sftp oSftp = new Sftp(_ftpURL, _UserName, _Password);
oSftp.Connect(_Port);
oSftp.Put(LocalDirectory + "/" + FileName, _ftpDirectory + "/" + FileName);
oSftp.Close();

In this way we can download, upload files in C#. Hope you all enjoy this article. We can also Download, Upload files from FTP Server in C# .

Rashedul Alam

I am a software engineer/architect, technology enthusiast, technology coach, blogger, travel photographer. I like to share my knowledge and technical stuff with others.

View all posts by Rashedul Alam →

22 thoughts on “Download, Upload files from SFTP Server in C#

    1. Dear Team,
      How to get last modified file date and time from Tahmir ssh. I’m not getting how to store in a variable.

  1. I too stuck with same issue as posted by Arun above.
    i.e. Throwing null reference exception while attempting to connect SFTP server.
    Please help me out..

    Thanks in advance,
    Chandu

  2. Hi, Thanks for the post.. when i tried i am getting the below error. Please advice.

    System.Net.Sockets.SocketException: The requested name is valid, but no data of the requested type was found
    at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
    at System.Net.Dns.GetHostByName(String hostName)
    at Tamir.SharpSsh.java.net.Socket..ctor(String host, Int32 port)
    at Tamir.SharpSsh.jsch.Util.createSocket(String host, Int32 port, Int32 timeout)

    Thanks,
    Dine.

  3. Hi ,
    Thanks for the post ; After adding code i am getting following error as
    System.Net.Sockets.SocketException (0x80004005): This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server
    at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
    at System.Net.Dns.GetHostByName(String hostName)
    at Tamir.SharpSsh.java.net.Socket..ctor(String host, Int32 port)
    at Tamir.SharpSsh.jsch.Util.createSocket(String host, Int32 port, Int32 timeout)

  4. i tried to download folders and sub-folders from sftp but in vain…here’s my code :-

    string[] s = Directory.GetFiles(ftpfolder,”*.txt”, SearchOption.AllDirectories);
    for(int i=0; i< s.length; i++)
    {
    osftp.Get(ftpfolder + s[i], localfolder + Path.GetfileName(s.[i]));
    }

  5. Hi , CybarLab Group.
    I was using a C# program that donwloads files from Sftp server,
    the C# program was originated from one of your important articles in website,
    it has been working fine since 2013/08/01 , but now when the program tries to connect to the Sftp server , there is an error : “Invalid Server’s version string”.
    So how can i solve it.

  6. What about downloading multiple files from the sftp if the file names have spaces or special characters?

    I loop through the list and get most but I have found where some files are being created like this.
    TestFile for yyyy-dd-mm hh-mm-ss-nnnn.txt in command line you can simply put double quotes around this to get it to download “TestFile for yyyy-dd-mm hh-mm-ss-nnnn.txt” . this does not seem to work when using the get();

    I have tried adding the quotes into the string and just in the get(“\”” + fileName + “\””, localpath) put this fails also. Any ideas?

  7. hello, while upload on sftp i am getting invalid server’s version String error please anyone can halp me ?

  8. Hi I tried the above code to put the file but i got the below error, please advise :

    An unhandled exception of type ‘Tamir.SharpSsh.jsch.JSchException’ occurred in Tamir.SharpSsh.dll
    Additional information: Session.connect: System.IO.FileNotFoundException: Could not load file or assembly ‘DiffieHellman, Version=0.0.0.0, Culture=neutral, PublicKeyToken

  9. Hi I have Installed Rebex Tiny SFTP Server on my local machine to teste is it working or not.
    after doing this itry to upload the file from local machine to serve. but its thrawing an execption as bellow kindly anyone help to me for the same.
    its thrawing an error when debugger comes in oSftp.Connect(_Port);
    Session.connect: System.NullReferenceException: Object reference not set to an instance of an object.

    at Tamir.SharpSsh.jsch.jce.HMACMD5.update(Byte[] foo, Int32 s, Int32 l)

    at Tamir.SharpSsh.jsch.jce.HMACMD5.update(Int32 i)

    at Tamir.SharpSsh.jsch.Session.read(Buffer buf)

    at Tamir.SharpSsh.jsch.UserAuth.start(Session session)

    at Tamir.SharpSsh.jsch.UserAuthNone.start(Session session)

    at Tamir.SharpSsh.jsch.Session.connect(Int32 connectTimeout)

  10. I am getting below error whicle i am using thin on visual studio 2013 and target framework 4.5
    but i am good in VS2017 with target framework 4.5 .
    Please help me why this is error out for vs2013

    Session.connect: System.NullReferenceException: Object reference not set to an instance of an object.

    at Tamir.SharpSsh.jsch.jce.HMACMD5.update(Byte[] foo, Int32 s, Int32 l)

    at Tamir.SharpSsh.jsch.jce.HMACMD5.update(Int32 i)

Leave a Reply

Your email address will not be published. Required fields are marked *