0

How can I check if the file exists in my FTP server? I am getting an catch exception because sometimes the file does not exists.

DateTime now = DateTime.Now;
            string repotroday = "report_" + now.Year.ToString() + "_" + now.Month.ToString() + "_" + now.Day.ToString() + ".csv";

            WebClient client = new WebClient();
            string url = "ftp://vps.myserver.com/" + repotroday;
            client.Credentials = new NetworkCredential("SURE", "iRent@123");
            string contents = client.DownloadString(url);

However, when I do not have the report in the FTP, it returns: The remote server returned an error: (550) File unavailable (e.g., file not found, no access)

Is there a way to check if the file exists before trying to download it?

Thanks

Max Boy
  • 317
  • 6
  • 21

1 Answers1

0

This is a method that I created for myself that looks like it does what you are looking for.

   private bool FileExists(string url, out int contentLength)
    {
        bool fileExistsAnswer;
        try 
        {
            WebRequest request = HttpWebRequest.Create(url);
            request.Method = "HEAD"; // Just get the document headers, not the data.    
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;    // This may throw a WebException:    
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    fileExistsAnswer = true;
                    contentLength = Convert.ToInt32(response.ContentLength);
                }
                else
                {
                    fileExistsAnswer = false;
                    contentLength = 0;
                }
            }            
        }
        catch(Exception Ex)
        {
            fileExistsAnswer = false;
            contentLength = 0;
        }

        return fileExistsAnswer;

    } // private bool FileExists(string url)

This is how I used it.

            string productThumbUrl = string.Empty;
            int contentLength;
            if (FileExists(productThumbUrl_png, out contentLength))
            {
                productThumbUrl = productThumbUrl_png;
            }
darryl
  • 104
  • 1
  • 4