Click here to Skip to main content
13,254,366 members (57,598 online)
Click here to Skip to main content
Add your own
alternative version

Stats

10.1K views
377 downloads
17 bookmarked
Posted 30 May 2017

SFTP File Upload with C# Application

, 11 Jun 2017
Rate this:
Please Sign up or sign in to vote.
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.

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.

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.

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.

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.

sftpClient.Connect();

Create an object of File Stream and pass file path.

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

You can set maximum buffer size in byte.

sftpClient.BufferSize =  1024;

Upload the file.

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

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

sftpClient.Dispose ();

The file has been copied to the remote location.

Complete Code

 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)

Share

About the Author

israrali
Pakistan Pakistan
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 12 Jun 2017
Article Copyright 2017 by israrali
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid