Surendra Sharma

Surendra Sharma

Search This Blog

Thursday, March 20, 2014

How to upload file via SFTP using private key in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to upload file to secure SFTP servers.

Here is simple and full code to upload 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 private key.

Note:- 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 the file and uploads the final stream to SFTP server.

using Renci.SshNet;

public static void UploadFileToSFTPServer(string FilePath, string Address, int Port, string UserName, string Password, string FolderName)
{
    SftpClient client = null;

    string sPrivateKeyPath = "PrivateKeyFilePath";
    PrivateKeyFile ObjPrivateKey = null;
    PrivateKeyAuthenticationMethod ObjPrivateKeyAutentication = null;
    using (Stream stream = File.OpenRead(sPrivateKeyPath))
    {
        if (ConfigurationSettings.AppSettings["PassPhraseCode"] != null)
        {
            string sPassPhrase = ConfigurationSettings.AppSettings["PassPhraseCode"];
            ObjPrivateKey = new PrivateKeyFile(stream, sPassPhrase);
            ObjPrivateKeyAutentication = new PrivateKeyAuthenticationMethod(UserName, ObjPrivateKey);
        }
        else
        {
            ObjPrivateKey = new PrivateKeyFile(stream);
            ObjPrivateKeyAutentication = new PrivateKeyAuthenticationMethod(UserName, ObjPrivateKey);
        }

        ConnectionInfo objConnectionInfo = new ConnectionInfo(Address, Port, UserName, ObjPrivateKeyAutentication);
        client = new SftpClient(objConnectionInfo);
    }
SftpClient client = new SftpClient(Address, Port, UserName, Password);


    client.Connect();

    if (!string.IsNullOrEmpty(FolderName))
    {
        client.ChangeDirectory(FolderName + @"/");
    }

    using (var fileStream = new FileStream(FilePath, FileMode.Open))
    {
        client.BufferSize = 4 * 1024;
        client.UploadFile(fileStream, Path.GetFileName(FilePath), null);
    }
    client.Disconnect();
    client.Dispose();


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

17 comments:

  1. Replies
    1. Learning Lessons For Sitecore, C, .Net, Sql Server: How To Upload File Via Sftp Using Private Key In Asp.Net Using C >>>>> Download Now

      >>>>> Download Full

      Learning Lessons For Sitecore, C, .Net, Sql Server: How To Upload File Via Sftp Using Private Key In Asp.Net Using C >>>>> Download LINK

      >>>>> Download Now

      Learning Lessons For Sitecore, C, .Net, Sql Server: How To Upload File Via Sftp Using Private Key In Asp.Net Using C >>>>> Download Full

      >>>>> Download LINK NN

      Delete
  2. I have used just upload part. Good one. thnx

    ReplyDelete
  3. Hi,

    Would be possible to have also an example with the download?

    Thanks

    Simone

    ReplyDelete
  4. Hi, Thanks for your SFTP program. When I tried the same applied all param data,and in the line client.Connect(); im getting "'Renci.SshNet.Common.SshAuthenticationException' occurred in Renci.SshNet.dll
    -Raja
    Additional information: No suitable authentication method found to complete authentication."
    Can you please explain what input is missing here.
    Please help on this

    ReplyDelete
  5. Hi Surendar, I have corrected the above error "client.Connect(); " posted by me.Currently im integrating it to winforms with controls. I tried to give progress bar for uploading big size files.Is there any events in Renci.SshNet?I could not see any events to write progress of uploading.Thanks.

    ReplyDelete
  6. Hi Surendar, I have to connect SFTP Server via Key Authentication only.So why i need to mentioned password in the code.
    i am little bit confusion on following code
    client = new SftpClient(objConnectionInfo);
    }
    SftpClient client = new SftpClient(Address, Port, UserName, Password);

    why above two client declarations?

    ReplyDelete
    Replies
    1. That was by mistake. Comment 2nd declaration for client

      Delete
    2. var sftp = new SftpClient(host, username, password)

      Delete
  7. Thanks for the help. It mostly works; but as of June 2018, there are 2 changes: 1. The library: https://github.com/sshnet/SSH.NET (just in case)
    2. Private key change is as per: https://stackoverflow.com/questions/13449525/sharpssh-invalid-privatekey

    ReplyDelete
  8. Thanks bro...u just save my time.

    ReplyDelete
  9. Thank you ... it's very helpfull. I use this code AS2 file transfer method

    ReplyDelete
  10. Hi Bro, i want to upload file in ASCII binary format. i have tried with above method, it shows uploaded file as unreadable format. please guide

    ReplyDelete
  11. We have sell some products of different custom boxes.it is very useful and very low price please visits this site thanks and please share this post with your friends. video upload

    ReplyDelete
  12. hello sir, when i am trying to pass private key file path , i am getting an error Invalid data type, INTEGER(02) is expected, but was 00.
    please help

    ReplyDelete