tags:

views:

9851

answers:

2

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?

A: 
                 FtpWebRequest ftpclientRequest = WebRequest.Create(args[0]) as FtpWebRequest;
                 ftpclientRequest.Method = FtpMethods.ListDirectoryDetails;

Source

More Discussion

kushin
This code is cut from a method to list catalog. What I search for is a method to check if a file exists.
tomaszs
FtpWebRequest.Method is FtpWebRequest, not FtpMethods. Therefore I can't test this code. There is no FtpMethods class in .NET 3.5
tomaszs
I think you might have to use the webrequestmethods.ftp members. check here: http://odetocode.com/Blogs/scott/archive/2005/11/26/2517.aspx
kushin
Thank you. But I can't get this done. This link does not have this method.
tomaszs
+11  A: 
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
Hello,I've put my user, and my password and set my URI.File exists but this code indicates that it does not exist
tomaszs
You are truely a genius ideed! It works like a charm!
tomaszs