How to Check if a File Exists in FTP Server in C#

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:

  1. private bool CheckIfFileExistsOnServer(string fileName)    
  2. {    
  3.     var request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/" + fileName);    
  4.     request.Credentials = new NetworkCredential("username""password");    
  5.     request.Method = WebRequestMethods.Ftp.GetFileSize;    
  6.     
  7.     try    
  8.     {    
  9.         FtpWebResponse response = (FtpWebResponse)request.GetResponse();    
  10.         return true;    
  11.     }    
  12.     catch (WebException ex)    
  13.     {    
  14.         FtpWebResponse response = (FtpWebResponse)ex.Response;    
  15.         if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)    
  16.             return false;    
  17.     }    
  18.     return false;    
  19. }  
As you see, we create an object of FtpWebRequest class and try to get the FileSize of the requested file. If the file exists, server will return the file size else it will throw an exception saying "File unavailable". In the catch block, we are catching the exception and checking for the ResponseCode from the response. If the ResponseCode is "ActionNotTakenFileUnavailable", this means the file is unavailable and we return to the calling method.

Hope you like this post. Keep learning & sharing! Cheers!

Ebook Download
View all
Learn
View all
Think. Innovate. Grow.