« Creating TCP/IP connections through an SSH server in .NET | Main | Communicating with an SMTP server and sending emails in .NET »

September 13, 2008

Securely transferring files over FTP in .NET

Overview

       This article will demonstrate how to securely transfer files over FTP using Secure FTP Factory for .NET

Code Example

       Download licenseSecureFTP.txt
  |  Download SecureFTP.cs   |  Download SecureFTPEx.vb

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Collections;
   4:  using System.Text;
   5:  using Jscape.Ftp;
   6:  using System.IO;
   7:   
   8:  namespace SecureFTPNET
   9:  {
  10:      class SecureFTP
  11:      {
  12:          Ftp ftp = null;
  13:   
  14:          public SecureFTP(string hostname, string username, string password)
  15:          {
  16:              ftp = new Ftp(hostname, username, password);
  17:              ftp.LicenseKey = null; // copy license from license.txt here
  18:              ftp.FtpConnectedEvent +=
  19:                  new FtpConnectEventHandler(ftp_FtpConnectedEvent);
  20:              ftp.FtpDisconnectedEvent +=
  21:                  new FtpConnectEventHandler(ftp_FtpDisconnectedEvent);
  22:          }
  23:   
  24:          private void ftp_FtpDisconnectedEvent(object sender, FtpConnectEventArgs e)
  25:          {
  26:              Console.WriteLine("Connected to : " + e.HostName);
  27:          }
  28:   
  29:          private void ftp_FtpConnectedEvent(object sender, FtpConnectEventArgs e)
  30:          {
  31:              Console.WriteLine("Disconnected from : " + e.HostName);
  32:          }
  33:   
  34:          public void setProxy(string proxyHost, int proxyPort, string proxyPassword)
  35:          {
  36:              ftp.ProxyHostname = proxyHost;
  37:              ftp.ProxyPort = proxyPort;
  38:              ftp.ProxyPassword = proxyPassword;
  39:          }
  40:   
  41:          public void changePassword(string oldPassword, string newPassword)
  42:          {
  43:              ftp.ChangePassword(oldPassword, newPassword);
  44:          }
  45:   
  46:          public void setImplicitSSLConnectionType()
  47:          {
  48:              this.ftp.ConnectionType = Ftp.IMPLICIT_SSL;
  49:          }
  50:   
  51:          public void setSecureConnectionType()
  52:          {
  53:              this.ftp.ConnectionType = Ftp.AUTH_TLS;
  54:          }
  55:   
  56:          public void openConnection()
  57:          {
  58:              ftp.Connect();
  59:          }
  60:   
  61:          public void closeConnection()
  62:          {
  63:              ftp.Disconnect();
  64:          }
  65:   
  66:          public void enableZipCompression(bool value)
  67:          {
  68:              ftp.Compression = value;
  69:          }
  70:   
  71:          public void setPort(int port)
  72:          {
  73:              ftp.Port = port;
  74:          }
  75:   
  76:          public void clearCommandChannel()
  77:          {
  78:              ftp.ClearCommandChannel();
  79:          }
  80:   
  81:          public void setClientCertificate(string cert)
  82:          {
  83:              ftp.SetClientCertificate(cert);
  84:          }
  85:   
  86:          public void setTrustedCertificate(string cert, string pass)
  87:          {
  88:              ftp.SetTrustedCertificates(cert, pass);
  89:          }
  90:   
  91:          public void setLocalDir(string dir)
  92:          {
  93:              ftp.LocalDir = dir;
  94:          }
  95:   
  96:          public void setRemoteDir(string dir)
  97:          {
  98:              ftp.RemoteDir = dir;
  99:          }
 100:   
 101:          // ArrayList items should be cast to FtpFile before use.
 102:          public ArrayList getLocalDirListing()
 103:          {
 104:              return GetArrayListFromEnumerator(ftp.LocalDirListing());
 105:          }
 106:   
 107:          // ArrayList items should be cast to FileInfo before use.
 108:          public ArrayList getRemoteDirListing()
 109:          {
 110:              return GetArrayListFromEnumerator(ftp.GetDirListing());
 111:          }
 112:   
 113:          public ArrayList sortListing(ArrayList lt,
 114:                                       bool sortOption,
 115:                                       FtpFileSort.Comparator compareOption)
 116:          {
 117:              FtpFileSort sort = new FtpFileSort(lt.GetEnumerator());
 118:              sort.Ascendent = sortOption;
 119:              return GetArrayListFromEnumerator(sort.Sort(compareOption));
 120:          }
 121:   
 122:          public ArrayList GetArrayListFromEnumerator(IEnumerator enumerator)
 123:          {
 124:              ArrayList ret = new ArrayList();
 125:              while (enumerator.MoveNext()) ret.Add(enumerator.Current);
 126:              return ret;
 127:          }
 128:   
 129:          public void uploadFile(string source, string dest, bool append,
 130:                                 TransferModes mode)
 131:          {
 132:              ftp.TransferMode = mode;
 133:              ftp.Upload(new FileInfo(source), dest, append);
 134:          }
 135:   
 136:          public FileInfo downloadFile(string file, TransferModes modes)
 137:          {
 138:              ftp.TransferMode = modes;
 139:              return ftp.Download(file);
 140:          }
 141:   
 142:          public void downloadDir(string dir)
 143:          {
 144:              ftp.DownloadDir(dir);
 145:          }
 146:   
 147:          public void downloadToStream(string file)
 148:          {
 149:              Stream inputStream = ftp.GetInputStream(file, 0);
 150:              Stream outputStream = File.Create(file);
 151:              byte[] buffer = new byte[8192];
 152:              int read = 0;
 153:              while ((read = inputStream.Read(buffer, 0, buffer.Length)) != 0)
 154:                  outputStream.Write(buffer, 0, read);
 155:              inputStream.Close();
 156:              outputStream.Close();
 157:              outputStream.Flush();
 158:          }
 159:   
 160:          public byte[] downloadToMemory(string rFile)
 161:          {
 162:              int buffersize = Convert.ToInt32(ftp.GetFileSize(rFile));
 163:              MemoryStream bout = new MemoryStream(buffersize);
 164:              ftp.Download(bout, rFile);
 165:              return bout.GetBuffer();
 166:          }
 167:   
 168:          public FileInfo resumeDownload(string file, TransferModes mode)
 169:          {
 170:              ftp.TransferMode = mode;
 171:              return ftp.ResumeDownload(file);
 172:          }
 173:   
 174:          public void uploadFromMemory(string str, string file)
 175:          {
 176:              str += "\r\n";
 177:              ftp.Upload(Encoding.Default.GetBytes(str), file);
 178:          }
 179:   
 180:          public void makeDir(string dir)
 181:          {
 182:              ftp.MakeDir(dir);
 183:          }
 184:   
 185:          public void deleteDir(string dir, bool recursive)
 186:          {
 187:              ftp.DeleteDir(dir, recursive);
 188:          }
 189:   
 190:          public void renameFile(string oldname, string newname)
 191:          {
 192:              ftp.RenameFile(oldname, newname);
 193:          }
 194:   
 195:          public void deleteFile(string file)
 196:          {
 197:              ftp.DeleteFile(file);
 198:          }
 199:   
 200:          public long getFileSize(string name)
 201:          {
 202:              return ftp.GetFileSize(name); 
 203:          }
 204:   
 205:          public DateTime getTimeStamp(string filename)
 206:          {
 207:              return ftp.GetFileTimeStamp(filename);
 208:          }
 209:   
 210:          public void uploadFromStream(string file)
 211:          {
 212:              FileInfo fileInfo = new FileInfo(file);
 213:              Stream inputStream = fileInfo.OpenRead();
 214:              Stream outputStream = ftp.GetOutputStream(fileInfo.Name, false, 0);
 215:              byte[] buffer = new byte[8192];
 216:              int read = 0;
 217:              while((read = inputStream.Read(buffer, 0, buffer.Length)) != 0)
 218:                  outputStream.Write(buffer, 0, read);
 219:              inputStream.Close();
 220:              outputStream.Close();
 221:              outputStream.Flush();
 222:          }
 223:   
 224:          static void Main(string[] args)
 225:          {
 226:              try
 227:              {
 228:                  string hostname = "[hostname]";
 229:                  string username = "[username]";
 230:                  string password = "[password]";
 231:                  SecureFTP sFTP = new SecureFTP(hostname, username, password);
 232:                  sFTP.openConnection();
 233:                  sFTP.closeConnection();
 234:              }
 235:              catch (Exception e)
 236:              {
 237:                  Console.WriteLine(e.Message);
 238:              }
 239:   
 240:              Console.WriteLine("Press any key to continue ... ");
 241:              Console.Read();
 242:          }
 243:      }
 244:  }

Lines 1-6   : Necessary import statements.
Lines 14-22 : Initialize Ftp instance and connect event handlers.
Lines 24-32 : Event handlers for connect/disconnect events.
Lines 34-39 : Use this method if a proxy is going to be used.
Lines 41-44 : Method to change password.
Lines 46-49 : Use Implict SSL to connect to the server.
Lines 51-54 : Use Exlpicit SSL to connect to the server.
Lines 56-64 : Methods to open/close connection to the server.
Lines 66-69 : Enable zip compression when performing file transfers or directory listings.
Lines 71-74 : Set connection port.
Lines 76-79 : Clear the command channel.
Lines 81-84 : Provide a client certificate.
Lines 86-89 : Provide a trusted server certificate.
Lines 91-94 : Set current local directory.
Lines 96-99 : Set the remote directory.
Lines 102-105 : Get local directory listing.
Lines 108-111 : Get remote directory listing.
Lines 113-120 : Sort a given directory listing.
Lines 129-134 : Upload a file.
Lines 136-140 : Download a file.
Lines 142-145 : Download a directory.
Lines 147-158 : Download a file to a Stream instance.
Lines 160-166 : Download file as a byte array.
Lines 168-172 : Resume download of a remote file.
Lines 174-178 : Upload from memory.
Lines 180-183 : Create a remote directory.
Lines 185-188 : Delete a remote directory.
Lines 190-193 : Rename a remote file.
Lines 195-198 : Delete a remote file.
Lines 200-203 : Get the size of a remote file.
Lines 205-108 : Get the timestamp of a remote file.
Lines 210-222 : Upload a file from a Stream.
Line 231      : Initialize SecureFTP instance.

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00e550fd70338833010534a7bb79970c

Listed below are links to weblogs that reference Securely transferring files over FTP in .NET:

Comments

Feed You can follow this conversation by subscribing to the comment feed for this post.

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been saved. Comments are moderated and will not appear until approved by the author. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

Comments are moderated, and will not appear until the author has approved them.