Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if file exists on FTP before FtpWebRequest

I need to use FtpWebRequest to put a file in a FTP directory. Before the upload, I would first like to know if this file exists.

What method or property should I use to check if this file exists?

like image 326
Tom Smykowski Avatar asked Dec 07 '08 18:12

Tom Smykowski


People also ask

How do I find my FTP folder?

This is a quick tip to access your FTP folder directly from your Operating System. Open a Windows explorer window (Windows key + E) and type the FTP address (ftp://domainname.com) in the file path at the top and hit Enter. Enter the username and password into the prompt window.


2 Answers

var request = (FtpWebRequest)WebRequest.Create     ("ftp://ftp.domain.com/doesntexist.txt"); request.Credentials = new NetworkCredential("user", "pass"); request.Method = WebRequestMethods.Ftp.GetFileSize;  try {     FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch (WebException ex) {     FtpWebResponse response = (FtpWebResponse)ex.Response;     if (response.StatusCode ==         FtpStatusCode.ActionNotTakenFileUnavailable)     {         //Does not exist     } } 

As a general rule it's a bad idea to use Exceptions for functionality in your code like this, however in this instance I believe it's a win for pragmatism. Calling list on the directory has the potential to be FAR more inefficient than using exceptions in this way.

If you're not, just be aware it's not good practice!

EDIT: "It works for me!"

This appears to work on most ftp servers but not all. Some servers require sending "TYPE I" before the SIZE command will work. One would have thought that the problem should be solved as follows:

request.UseBinary = true; 

Unfortunately it is a by design limitation (big fat bug!) that unless FtpWebRequest is either downloading or uploading a file it will NOT send "TYPE I". See discussion and Microsoft response here.

I'd recommend using the following WebRequestMethod instead, this works for me on all servers I tested, even ones which would not return a file size.

WebRequestMethods.Ftp.GetDateTimestamp 
like image 80
user42467 Avatar answered Sep 23 '22 19:09

user42467


Because

request.Method = WebRequestMethods.Ftp.GetFileSize 

may fails in some case (550: SIZE not allowed in ASCII mode), you can just check Timestamp instead.

reqFTP.Credentials = new NetworkCredential(inf.LogOn, inf.Password); reqFTP.UseBinary = true; reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp; 
like image 26
Nolmë Informatique Avatar answered Sep 25 '22 19:09

Nolmë Informatique