65.9K
CodeProject is changing. Read more.
Home

Upload File to SFTP Site with C# in Visual Studio .NET

starIconstarIconstarIconstarIconstarIcon

5.00/5 (10 votes)

Jul 7, 2016

CPOL

1 min read

viewsIcon

165117

How to Use SSH.NET in Visual Studio 2015 to upload a file to an SFTP site

Introduction

This is a simple solution for uploading files to an SFTP server from .NET Framework using Visual Studio 2015.

The SSH package offers many more options that can be explored. For the purposes of this tip, I am only concentrating on a simple file transfer from a local server to an SFTP site (Upload).

Background

After searching for 2 days, I finally came across a solution out of Belgium that allowed me to programmatically upload a file to an SFTP server. There is not a lot of documentation out there on the use of SSH.Net, so I hope you find this useful. Credit to http://blog.deltacode.be/2012/01/05/uploading-a-file-using-sftp-in-c-sharp/ for the original posting of this fix. Since so many of my colleagues utilize Code Project, I felt it would be a good location to add this information.

Using the Code

In your Solution / Project:

Select Manage NuGet Packages and search for and select SSH.Net --> Install Latest Stable Version (2013.4.7) supports .NET 3.5 and 4.0

Add New Blank Class to your project - then add the following code to your class.

using Renci.SshNet;
using System.IO;

namespace YourProjectNamespace
{
 class sftp
 {
  public static void UploadSFTPFile(string host, string username, 
  string password, string sourcefile, string destinationpath, int port)
  {
   using (SftpClient client = new SftpClient(host, port, username, password))
   {
    client.Connect();
    client.ChangeDirectory(destinationpath);
    using (FileStream fs = new FileStream(sourcefile, FileMode.Open))
    {
     client.BufferSize = 4 * 1024;
     client.UploadFile(fs, Path.GetFileName(sourcefile));
    }
   }
  }
 }
}

**********************

In your event call, pass the needed parameters for your file to upload:

        string source = @"FilePath and FileName of Local File to Upload";
        string destination = @"SFTP Server File Destination Folder";
        string host = "SFTP Host";
        string username = "User Name";
        string password = "password";
        int port = 22;  //Port 22 is defaulted for SFTP upload
        
        sftp.UploadSFTPFile(host, username, password, source, destination, port);

History

  • 7th July, 2016: Initial version