Click here to Skip to main content
15,883,873 members
Articles / Programming Languages / ASP
Tip/Trick

SFTP File Upload with C# Application

Rate me:
Please Sign up or sign in to vote.
3.35/5 (7 votes)
11 Jun 2017CPOL2 min read 66.1K   2.5K   19   5
A brief code snippet to upload the file to the server or remote location with SFTP in Visual Studio C#

Introduction

Secure file transfer protocol (SFTP) is one of the approaches to uploading to the server remotely over a secure and encrypted connection. In .NET, we can easily develop a utility to perform the mentioned task.

For this, all we need to do is to use an assembly called SSH.NET. SSH.NET is a Secure Shell (SSH) library for.NET, optimized for parallelism and with broad framework support.

Image 1

We can install this library by executing the following command in package manager console.

Install-Package SSH.NET -Version 2016.0.0

Background

In order to understand the tip, basic knowledge/understanding of object-oriented programming is required.

Problem

I was given a task to upload the file to the remote server through schedule job. I found a few articles on the internet but all of them were ambiguous, incomplete and not clear in vision. That's why I decided to write an article in the easiest way for the developer.

Why Prefer SFTP over HTTP

Although we can perform the same task using HTTP but it has drawbacks to use HTTP for file upload. HTTP is basically used for download the file or to upload small file on the server. In a normal scenario, Html form is used to submit the file and browser has timeout issue for a large file.

Coding Steps

Create a new project in Visual Studio.

Incorporate SSH.NET by executing the mentioned command in package manager console.

Add the following namespaces in the file.

C#
using Renci.SshNet;
using Renci.SshNet.Sftp;

Create an object of SftpClient and provide connection information parameter in different overload.

We can pass host, port, username, password directly into the constructor.

C#
SftpClient client = new SftpClient (host, port, username, password);

OR

We can also create a connection info object and pass to sftpClient’s constructor with the public key.

C#
SftpClient sftpClient = new SftpClient (getSftpConnection ("Host", "username", port, "publicKeyPath"));

public static ConnectionInfo getSftpConnection
(string host, string username, int port, string publicKeyPath)
{
  return new ConnectionInfo(host, port, username, privateKeyObject(username, publicKeyPath));
}

private static AuthenticationMethod[] privateKeyObject(string username, string publicKeyPath)
{
  PrivateKeyFile privateKeyFile = new PrivateKeyFile(publicKeyPath);
  PrivateKeyAuthenticationMethod privateKeyAuthenticationMethod =
       new PrivateKeyAuthenticationMethod(username, privateKeyFile);
  return new AuthenticationMethod[] { privateKeyAuthenticationMethod };
}

Connect SftpClient.

C#
sftpClient.Connect();

Create an object of File Stream and pass file path.

C#
FileStream fs = new FileStream("filePath", FileMode.Open);

You can set maximum buffer size in byte.

C#
sftpClient.BufferSize =  1024;

Upload the file.

C#
sftpClient.UploadFile(fs, Path.GetFileName("filePath"));

Dispose the object by calling dispose method of sftpClient once the file has uploaded.

C#
sftpClient.Dispose ();

The file has been copied to the remote location.

Complete Code

C#
 static void Main(string[] args)
    {
            Console.WriteLine("Create client Object");
            using (SftpClient sftpClient = new SftpClient(getSftpConnection
                                           ("host", "userName", 22, "filePath")))
            {
                Console.WriteLine("Connect to server");
                sftpClient.Connect();
                Console.WriteLine("Creating FileStream object to stream a file");
                using (FileStream fs = new FileStream("filePath", FileMode.Open))
                {
                    sftpClient.BufferSize = 1024;
                    sftpClient.UploadFile(fs, Path.GetFileName("filePath"));
                }
                sftpClient.Dispose();
            }
     } 

public static ConnectionInfo getSftpConnection
(string host, string username, int port, string publicKeyPath)
{
   return new ConnectionInfo(host, port, username, privateKeyObject(username, publicKeyPath));
}

private static AuthenticationMethod[] privateKeyObject(string username, string publicKeyPath)
{
  PrivateKeyFile privateKeyFile = new PrivateKeyFile(publicKeyPath);
  PrivateKeyAuthenticationMethod privateKeyAuthenticationMethod = 
     new PrivateKeyAuthenticationMethod(username, privateKeyFile);
      return new AuthenticationMethod[]   
       {
        privateKeyAuthenticationMethod 
       };
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSFTP File upload Pin
ajaykumar052916-Apr-20 18:55
ajaykumar052916-Apr-20 18:55 
QuestionI am trying to upload .csv file into SFTP server , but getting this msg - Could not load file or assembly 'Renci.SshNet, Version=2016.0.0.0, Culture=neutral, PublicKeyToken=1cee9f8bde3db106' or one of its dependencies. The system cannot find the fil Pin
Member 1231544227-Aug-19 23:20
Member 1231544227-Aug-19 23:20 
QuestionQuestion. Pin
Member 141109958-Jan-19 20:58
Member 141109958-Jan-19 20:58 
QuestionGetting-Exception Pin
Member 129069617-Mar-18 5:53
Member 129069617-Mar-18 5:53 
AnswerRe: Getting-Exception Pin
Member 141109959-Jan-19 14:36
Member 141109959-Jan-19 14:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.