Market Data Unfair Advantage Posting Status Robert 2016

How to download files from FTP or SFTP in C#

FTP

Use the below code to download a file from an FTP server with C#.

Code Snippet
  1. using System.Net;
  2. using System.IO;
  3.     
  4. String RemoteFtpPath = "ftp://ftp.csidata.com:21/Futures.20150305.gz";
  5. String LocalDestinationPath = "Futures.20150305.gz";
  6. String Username="yourusername";
  7. String Password = "yourpassword";
  8. Boolean UseBinary = true; // use true for .zip file or false for a text file
  9. Boolean UsePassive = false;
  10.  
  11. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(RemoteFtpPath);
  12. request.Method = WebRequestMethods.Ftp.DownloadFile;
  13. request.KeepAlive = true;
  14. request.UsePassive = UsePassive;
  15. request.UseBinary = UseBinary;
  16.  
  17. request.Credentials = new NetworkCredential(Username, Password);
  18.  
  19. FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  20.  
  21. Stream responseStream = response.GetResponseStream();
  22. StreamReader reader = new StreamReader(responseStream);
  23.  
  24. using (FileStream writer = new FileStream(LocalDestinationPath, FileMode.Create))
  25. {
  26.  
  27.     long length = response.ContentLength;
  28.     int bufferSize = 2048;
  29.     int readCount;
  30.     byte[] buffer = new byte[2048];
  31.  
  32.     readCount = responseStream.Read(buffer, 0, bufferSize);
  33.     while (readCount > 0)
  34.     {
  35.         writer.Write(buffer, 0, readCount);
  36.         readCount = responseStream.Read(buffer, 0, bufferSize);
  37.     }
  38. }
  39.  
  40. reader.Close();
  41. response.Close();

SFTP

First you must download and compile the SSH.Net library. Add the compiled .dll as a reference to your project.

Code Snippet
  1. using System.IO;
  2. using Renci.SshNet;
  3. using Renci.SshNet.Common;
  4. using Renci.SshNet.Sftp;
  5.  
  6. String Host = "ftp.csidata.com";
  7. int Port = 22;
  8. String RemoteFileName = "TheDataFile.txt";
  9. String LocalDestinationFilename = "TheDataFile.txt";
  10. String Username = "yourusername";
  11. String Password = "yourpassword";
  12.  
  13. using (var sftp = new SftpClient(Host, Port, Username, Password))
  14. {
  15.     sftp.Connect();
  16.  
  17.     using (var file = File.OpenWrite(LocalDestinationFilename))
  18.     {
  19.         sftp.DownloadFile(RemoteFileName, file);
  20.     }
  21.  
  22.     sftp.Disconnect();
  23. }