10.21.2009

File transfer using SFTP in C#

Before we delve into how we accomplish this, let's first find some common ground on what S-F-T-P means. In wikipedia, you'll get a longer than expected list of links for this acronym. The technology we want to utilize is SSH File Transfer Protocol. It is alternately known as Secure File Transfer Protocol, but to avoid confusion (hopefully) we will refer to it as SFTP henceforth. Please don't get it confused with "FTP over SSH" as it is a completely different protocol. SFTP runs on TCP port 22, the port commonly used for Secure Shell - SSH. "FTP over SSH" uses the standard TCP ports 20/21.

At this point, your boss asks you to send a file over to a vendor's [S]FTP server. After you do some research and figure out that he really means SSH File Transfer Protocol, the battle is half won. You can simply send that file using most ftp programs available. I had no idea. I personally use CoreFTP and was pleasantly surprised to find a nice little SSH/SFTP checkbox in the bottom right corner of the connection screen.



Now you want an api. SharpSSH is such a library that does SFTP along with a host of other things. Download demos and source files here.

Here is how simple it is to encrypt a file by using PGP.  I decided to go with the open source route.  Gnu Privacy Guard provides a simple wrapper class that makes it easy to encrypt/decrypt messages:

StreamReader reader = new StreamReader(readFromFile);
StreamWriter writer = new StreamWriter(writeToFile);
string output = "";

// Begin encryption
GnuPGWrapper wrapper = new GnuPGWrapper();

wrapper.homedirectory = "C:\\gnupg";
wrapper.passphrase = "";
wrapper.originator = "";
wrapper.recipient = "blah@blah.com";
wrapper.command = Commands.Encrypt;
wrapper.verbose = VerboseLevel.VeryVerbose;
wrapper.ExecuteCommand(reader.ReadToEnd(), out output);

writer.Write(output);