Click here to Skip to main content
15,921,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to upload files to FTP. Even before uploading, I need to check if the files exists in FTP. I am using this method to check if the file exists
C#
private bool FtpDirectoryExists(string dirPath, string FTPUser, string FTPPassword)
       {
           bool IsExists = true;
           try
           {
               FtpWebRequest request = (FtpWebRequest)WebRequest.Create(dirPath);
               request.Credentials = new NetworkCredential(FTPUser, FTPPassword);
               request.Method = WebRequestMethods.Ftp.ListDirectory;
               FtpWebResponse response = (FtpWebResponse)request.GetResponse();
               //response.Close();
           }
           catch (WebException ex)
           {
               IsExists = false;
           }
           return IsExists;
       }

It always returns true, even if the file doesnt exist..Can anyone please help me out
Posted
Updated 28-Jul-11 3:02am
v2
Comments
Yuri Vital 28-Jul-11 8:45am    
What is the content of response object ?

1 solution

Have a look here

How to check if a file exists on an FTP server[^]

Code from that tip

C#
public bool CheckIfFtpFileExists(string fileUri) 
{ 
    FtpWebRequest request = WebRequest.Create(fileUri); 
    request.Credentials = new NetworkCredential("username", "password"); 
    request.Method = WebRequestMethods.Ftp.GetFileSize; 
    try 
    { 
        FtpWebResponse response = request.GetResponse(); 
        // THE FILE EXISTS 
    } catch(WebException ex) 
    { 
        FtpWebResponse response = ex.Response; 
        if (FtpStatusCode.ActionNotTakenFileUnavailable == response.StatusCode)
        { 
            // THE FILE DOES NOT EXIST 
            return false; 
        } 
     } 
     return true; 
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900