0

I'm working on an ASP.NET MVC 5.1 web site, and I need to show a picture if it exists in an ftp server (CDN). Foldername and filename are tied to rules so I know them beforehand. I need to display a message if this file does not exist.

How can I check if this file exists?

Suggested duplicate (Verify if file exists or not in C#) does not help since I need to check if the file exists on a remote server and not a local folder.

Community
  • 1
  • 1
A. Burak Erbora
  • 1,054
  • 2
  • 12
  • 26
  • 1
    This is your sample problem : [enter link description here](http://stackoverflow.com/questions/347897/how-to-check-if-file-exists-on-ftp-before-ftpwebrequest) – Linh Tuan Oct 15 '15 at 07:23

1 Answers1

3

Try the following code

  string destination = "ftp://something.com/";
    string file = "test.jpg";
    string extention = Path.GetExtension(file);
    string fileName = file.Remove(file.Length - extention.Length);
    string fileNameCopy = fileName;
    int attempt = 1;

    while (!CheckFileExists(GetRequest(destination + "//" + fileNameCopy + extention)))
    {
        fileNameCopy = fileName + " (" + attempt.ToString() + ")";
        attempt++;
    }

    // do your upload, we've got a name that's OK
}

private static FtpWebRequest GetRequest(string uriString)
{
    var request = (FtpWebRequest)WebRequest.Create(uriString);
    request.Credentials = new NetworkCredential("", "");
    request.Method = WebRequestMethods.Ftp.GetFileSize;

    return request;
}

private static bool checkFileExists(WebRequest request)
{
    try
    {
        request.GetResponse();
        return true;
    }
    catch
    {
        return false;
    }
}

Reference from FTP Check if file exist

Community
  • 1
  • 1
Manraj
  • 496
  • 2
  • 15