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:
- private string DeleteFile(string fileName)
- {
- FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/" + fileName);
- request.Method = WebRequestMethods.Ftp.DeleteFile;
- request.Credentials = new NetworkCredential("username", "password");
-
- using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
- {
- return response.StatusDescription;
- }
- }
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!