Easy C# FTP Class

I created this class for use in a variety of applications as a simplified FTP client.  It’s versatile and simple to use.  Here are examples of using the class:

/* Create Object Instance */
ftp myFtpClient = new ftp(@”ftp://10.10.10.10/”, “user”, “password”);

/* Upload a File */
myFtpClient.upload(“etc/test.txt”, @”C:\Users\metastruct\Desktop\test.txt”);

/* Download a File */
myFtpClient.download(“etc/test.txt”, @”C:\Users\metastruct\Desktop\test.txt”);

/* Delete a File */
myFtpClient.delete(“etc/test.txt”);

/* Rename a File */
myFtpClient.rename(“etc/test.txt”, “test2.txt”);

/* Create a New Directory */
myFtpClient.createDirectory(“etc/test”);

/* Get the Date/Time a File was Created */
string fileDateTime = myFtpClient.getFileCreatedDateTime(“etc/test.txt”);
Console.WriteLine(fileDateTime);

/* Get the Size of a File */
string fileSize = myFtpClient.getFileSize(“etc/test.txt”);
Console.WriteLine(fileSize);

/* Get Contents of a Directory (Names Only) */
string[] simpleDirectoryListing = myFtpClient.directoryListDetailed(“/etc”);
for (int i = 0; i < simpleDirectoryListing.Count(); i++) { Console.WriteLine(simpleDirectoryListing[i]); }

/* Get Contents of a Directory with Detailed File/Directory Info */
string[] detailDirectoryListing = myFtpClient.directoryListDetailed(“/etc”);
for (int i = 0; i < detailDirectoryListing.Count(); i++) { Console.WriteLine(detailDirectoryListing[i]); }

myFtpClient = null;

Here is the code:

class ftp
{

private string host = null;
private string user = null;
private string pass = null;
private FtpWebRequest ftpRequest = null;
private FtpWebResponse ftpResponse = null;
private Stream ftpStream = null;
private int bufferSize = 2048;

/* Construct Object */
public ftp(string hostIP, string userName, string password) { host = hostIP; user = userName; pass = password; }

/* Download File */
public void download(string remoteFile, string localFile)
{

try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + “/” + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Get the FTP Server’s Response Stream */
ftpStream = ftpResponse.GetResponseStream();
/* Open a File Stream to Write the Downloaded File */
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);

/* Download the File by Writing the Buffered Data Until the Transfer is Complete */
try
{

while (bytesRead > 0)
{

localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);

}

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }

/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;

}

/* Upload File */
public void upload(string remoteFile, string localFile)
{

try
{

/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + “/” + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
/* Establish Return Communication with the FTP Server */
ftpStream = ftpRequest.GetRequestStream();
/* Open a File Stream to Read the File for Upload */
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
/* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
try
{

while (bytesSent != 0)
{

ftpStream.Write(byteBuffer, 0, bytesSent);
bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);

}

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpRequest = null;

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;

}

/* Delete File */
public void delete(string deleteFile)
{

try
{

/* Create an FTP Request */
ftpRequest = (FtpWebRequest)WebRequest.Create(host + “/” + deleteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Resource Cleanup */
ftpResponse.Close();
ftpRequest = null;

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;

}

/* Rename File */
public void rename(string currentFileNameAndPath, string newFileName)
{

try
{

/* Create an FTP Request */
ftpRequest = (FtpWebRequest)WebRequest.Create(host + “/” + currentFileNameAndPath);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.Rename;
/* Rename the File */
ftpRequest.RenameTo = newFileName;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Resource Cleanup */
ftpResponse.Close();
ftpRequest = null;

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;

}

/* Create a New Directory on the FTP Server */
public void createDirectory(string newDirectory)
{

try
{

/* Create an FTP Request */
ftpRequest = (FtpWebRequest)WebRequest.Create(host + “/” + newDirectory);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Resource Cleanup */
ftpResponse.Close();
ftpRequest = null;

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;

}

/* Get the Date/Time a File was Created */
public string getFileCreatedDateTime(string fileName)
{

try
{

/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + “/” + fileName);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Establish Return Communication with the FTP Server */
ftpStream = ftpResponse.GetResponseStream();
/* Get the FTP Server’s Response Stream */
StreamReader ftpReader = new StreamReader(ftpStream);
/* Store the Raw Response */
string fileInfo = null;
/* Read the Full Response Stream */
try { fileInfo = ftpReader.ReadToEnd(); }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
/* Return File Created Date Time */
return fileInfo;

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Return an Empty string Array if an Exception Occurs */
return “”;

}

/* Get the Size of a File */
public string getFileSize(string fileName)
{

try
{

/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + “/” + fileName);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Establish Return Communication with the FTP Server */
ftpStream = ftpResponse.GetResponseStream();
/* Get the FTP Server’s Response Stream */
StreamReader ftpReader = new StreamReader(ftpStream);
/* Store the Raw Response */
string fileInfo = null;
/* Read the Full Response Stream */
try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
/* Return File Size */
return fileInfo;

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Return an Empty string Array if an Exception Occurs */
return “”;

}

/* List Directory Contents File/Folder Name Only */
public string[] directoryListSimple(string directory)
{

try
{

/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + “/” + directory);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Establish Return Communication with the FTP Server */
ftpStream = ftpResponse.GetResponseStream();
/* Get the FTP Server’s Response Stream */
StreamReader ftpReader = new StreamReader(ftpStream);
/* Store the Raw Response */
string directoryRaw = null;
/* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + “|”; } }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
/* Return the Directory Listing as a string Array by Parsing ‘directoryRaw’ with the Delimiter               you Append (I use | in This Example) */
try { string[] directoryList = directoryRaw.Split(“|”.ToCharArray()); return directoryList; }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Return an Empty string Array if an Exception Occurs */
return new string[] { “” };

}

/* List Directory Contents in Detail (Name, Size, Created, etc.) */
public string[] directoryListDetailed(string directory)
{

try
{

/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + “/” + directory);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Establish Return Communication with the FTP Server */
ftpStream = ftpResponse.GetResponseStream();
/* Get the FTP Server’s Response Stream */
StreamReader ftpReader = new StreamReader(ftpStream);
/* Store the Raw Response */
string directoryRaw = null;
/* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + “|”; } }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
/* Return the Directory Listing as a string Array by Parsing ‘directoryRaw’ with the Delimiter               you Append (I use | in This Example) */
try { string[] directoryList = directoryRaw.Split(“|”.ToCharArray()); return directoryList; }
catch (Exception ex) { Console.WriteLine(ex.ToString()); }

}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Return an Empty string Array if an Exception Occurs */
return new string[] { “” };

}

}

Be sure to leave a comment if this helps or if you have any suggestions!

Advertisements
Tagged with: , , , ,
Posted in C#, FTP
15 comments on “Easy C# FTP Class
  1. Herve says:

    Hi
    What is the name of instance (using…) of FtpWebRequest and FtpWebResponse ??

  2. Juan Sebastian Alvarez Eraso says:

    Hi

    Your code is very helpfully for download and delete files from FTP server but I have a problem whit this lines to upload a file:


    FileStream localFileStream = new FileStream(localFile, FileMode.Create);
    /* Buffer for the Downloaded Data */
    byte[] byteBuffer = new byte[bufferSize];
    int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);

    always the “bytesSent” value is 0 and I don´t why

    can you help me ?? any suggestion ??

    thanks

    • Juan Sebastian Alvarez Eraso says:

      Hi,

      I changed the “FileMode” from this line:

      FileStream localFileStream = new FileStream(localFile, FileMode.Create);

      to:

      FileStream localFileStream = new FileStream(localFile, FileMode.Open);

      and it works !!

      Thanyou anyway

  3. wardah says:

    im completely new to ftp. can you tell me how to use this code. which server to use?

    • metastruct says:

      FTP is used to send files between computers. It can be useful for automation purposes and when files are too large to email or otherwise transfer. The server would depend on your needs for getting or sending files. If you have two computers on the same network, this code could act as the client, but you need to have the other computer configured as the server. There are examples on the internet for setting up the server with c#, or you could use FileZilla. I use this code mainly for automated file backups and generating reports based on data from remote servers. I hope that answers your question.

  4. wardah says:

    thanks for the help. i was able to complete my project and submit it today. Solved the server issue by creating an ftp site. your code was very helpful thank you.

  5. Scott says:

    Hi, I can retrieve the filename list ok from our ftp server but when I try to download the file by using the file name I’m getting the error. The remote server returned an error: (426) Connection closed; transfer aborted.

    Any ideas?

    • metastruct says:

      I would make sure you are using the absolute file path. Also, try using with and without binary mode. Could possibly be on the server side if you have the same issue using dos command prompt manually.

  6. Dan says:

    Thank you. I think it’s very useful! I will use your class for my new application.

  7. Sid says:

    How would you handle the situation where multiple files need to be downloaded in one FTP session? Specifically, what would you do to ensure all files of a certain extension, say .xml, are downloaded when requested?

    • metastruct says:

      Good question! Short answer: I don’t think that’s possible with this example without reconnecting. The closest solution I know would work is doing a loop on the download method but that would reconnect each time. Example:

      ftp myFtpClient = new ftp(@”ftp://10.10.10.10/”, “user”, “password”);

      string[] remote_files = new string[]
      {
      @“etc/test1.txt”,
      @“etc/test2.txt”
      };
      string[] local_files = new string[]
      {
      @”C:\Users\metastruct\Desktop\test1.txt”,
      @”C:\Users\metastruct\Desktop\test2.txt”
      };

      for (int i = 0; i < remote_files.Count(); i++)
      {
      myFtpClient.download(remote_files[i], local_files[i]);
      }

  8. Yogesh Chaudhari says:

    thanks for this class. but i want ftp over SSL. can i used same class for my requirement. pls help

  9. […] 2)  This is ONLY for SFTP.  For regular FTP check out my other post here. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: