Surendra Sharma

Surendra Sharma

Search This Blog

Friday, March 28, 2014

How to download file via SFTP in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to download file from secure SFTP server.

Here is simple and full code to download file via SFTP.

First you need to download SshNet DLL from http://sshnet.codeplex.com/.

You can connect SFTP by two ways
1.    By using credentials
2.    By using Username and private key. Private Key may be bind with Pass phrase.

This code is specific to connect to SFTP by using credentials.

Note:-
·         To connect by using private key refer my another article on the blog.
·         Your private key must be compatible with SshNet. To convert any private key to SshNet compatible private key, refer my other article How to convert Private key to OpenSSH Key to connect to SFTP server.

It uses SftpClient for creating SFTP connection to server by providing SFTP URL with credentials and private key to connect to specific folder or root folder. Code read and download the file from SFTP server.

using Renci.SshNet;

private static object threadLock = new object();

public static bool SFTPDownloadFile(string Address, string UserName, int Port, string Password, string DownloadFileName, string ServerFileName)
{
    SftpClient client = null;
    bool bReturnValue = false;

    try
    {

        client = new SftpClient(Address, Port, UserName, Password);

        client.Connect();

        lock (threadLock)
        {
            using (var file = File.OpenWrite(DownloadFileName))
            {
                client.DownloadFile(ServerFileName, file);
                bReturnValue = true;
            }
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

    finally
    {
        if (client != null)
        {
            client.Disconnect();
            client.Dispose();
        }
    }
    return bReturnValue;
}


Please leave your comments or share this code if it’s useful for you.

No comments:

Post a Comment