Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to communicate with SFTP server

Tags:

c#

.net

sftp

I've written a service for our customer that automatically transmits files to given destinations using FTP. For historic reasons I'm using WinInet to perform the FTPing. All works well, but now the customer wants to add one destination that only accepts SFTP connections.

I do not really like the idea of implementing this from scratch, so is there a way to communicate natively or through WinInet with a SFTP server? Are there any system libraries that I can use (I have no fear of P/Invoke :) )? Do I have to purchase third party components for that - if so, which ones would you suggest?

like image 361
Thorsten Dittmar Avatar asked Dec 10 '09 13:12

Thorsten Dittmar


People also ask

How does SFTP communication work?

When a client system requests a file transfer, SFTP creates a secure connection between the client and the SFTP server. This connection usually goes through port 22. SFTP then uses the SSH protocol to encrypt the requested file and transfer it to the client.

Can I SSH into SFTP server?

SFTP cannot exist without SSH — SFTP uses SSH as the binding agent to transfer files securely. In other words, SSH protocol is used in the file transfer mechanism SFTP. In fact, most SSH servers include SFTP capabilities. However, not all SFTP servers support SSH commands and actions.


Video Answer


1 Answers

There's no support for SFTP in .NET framework, in any version.


You have to use a third party library for SFTP.

You can use WinSCP .NET assembly. There's even a WinSCP NuGet package.

A trivial SFTP upload C# example:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Sftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
    SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Upload files
    session.PutFiles(@"d:\toupload\*", "/home/user/").Check();
}

There are lot of other examples.


You can have WinSCP GUI generate an SFTP code template, like above, for you, including C#, VB.NET and PowerShell.

enter image description here


The assembly is just a wrapper around WinSCP scripting, so it's not a completely native .NET code. As such it does not fit all use cases in .NET framework. It is mostly suitable for automating tasks, somewhat for developing GUI applications, and not really for web applications.

For a fully native .NET SFTP library, see SSH.NET, which is strangely not mentioned in any answer yet.

(I'm the author of WinSCP)


Windows 10 also come with command-line OpenSSH sftp client. It can also be downloaded for older versions of Windows.

like image 121
Martin Prikryl Avatar answered Oct 25 '22 07:10

Martin Prikryl