How To Delete a File From FTP Server in C#

Friends,

In my last post, we saw how can we retrieve the list of all files & folders from a FTP server using C#. In this post, we will see how can we delete a file from FTP server using C# from within your Console or Windows Forms Application.

Here's the code:

  1. private string DeleteFile(string fileName)    
  2. {    
  3.    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/" + fileName);    
  4.    request.Method = WebRequestMethods.Ftp.DeleteFile;    
  5.    request.Credentials = new NetworkCredential("username""password");    
  6.     
  7.    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())    
  8.    {    
  9.       return response.StatusDescription;        
  10.    }    
  11. }    
The above code deletes a file named "test.zip" from the root location of the server "www.server.com". If you see the code, we created an object of FtpWebRequest class and this time, we passed the RequestMethod as DeleteFile. This command tells the CLR to delete the mentioned file from the server. If the file is deleted, it sends a response in ResponseDescription as "250 File deleted successfully."

Hope you like this post! Keep learning and sharing! Cheers!

Rebin Infotech
Think. Innovate. Grow.