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, 5:28 AM
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, 11:08 AM
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, 7:55 AM
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, 11:26 AM
Nice one
Former memberPosted Feb 27, 2015, 1:54 PM
nice