Friends,
In my last post, we saw how we can delete a file from FTP server. However, there might be a situation when you try to delete a file and the file does not exist on the server. In this case, code will throw an error saying "550, File Unavailable". To solve this, we must know whether a file exists on server before accessing the file. In this post, we will see how we can do the same.
Here's the code:
- private bool CheckIfFileExistsOnServer(string fileName)
- {
- var request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/" + fileName);
- request.Credentials = new NetworkCredential("username", "password");
- request.Method = WebRequestMethods.Ftp.GetFileSize;
- try
- {
- FtpWebResponse response = (FtpWebResponse)request.GetResponse();
- return true;
- }
- catch (WebException ex)
- {
- FtpWebResponse response = (FtpWebResponse)ex.Response;
- if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
- return false;
- }
- return false;
- }
Hope you like this post. Keep learning & sharing! Cheers!


pradeep pradyumnaPosted Jun 13, 2019, 1:28 AM EDT
Nice article. Just a small refactor, you can remove that last statement "return false" as it will still compile since there one return statement written in catch block already
Eliezer GamezPosted Sep 26, 2018, 7:08 AM EDT
Hello, excellent article, thank you very much.Now I'm trying to know if it's possible to connect to the FTP server first of all. I guess it would give me a corresponding exception, in that case, which exception should I capture that indicates me connection failure? PS: I have all the correct credentials, but sometimes the connection fails and that is bringing me problems.
Abhishek ShrivastavaPosted May 16, 2017, 3:55 AM EDT
Thank you for the article. I have used the same approach to check whether file exists in ftp server or not but every time I am getting error "Unable to connect to the remote server". Please suggest how to fix it.
santosh tiwariPosted Apr 24, 2015, 7:26 AM EDT
Nice one
Former memberPosted Feb 27, 2015, 8:54 AM EST
nice