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) {
This is usually a bad idea to use Exceptions for functionality in your code like this, but in this case I consider this a victory for pragmatism. A list of calls in a directory may be more inefficient than using exceptions in this way.
If you do not, just know that this is not good practice!
EDIT: "This works for me!"
This seems to work on most ftp servers, but not all. Some servers require sending "TYPE I" before the SIZE command will work. It would seem that the problem should be solved as follows:
request.UseBinary = true;
Unfortunately, this is a design limitation (a big fat mistake!), If FtpWebRequest doesnβt upload or download the file, it DOES NOT send "TYPE I". See Microsoft Discussion and Answer here .
Instead, I recommend using the following WebRequestMethod, this works for me on all tested servers, even those that do not return file size.
WebRequestMethods.Ftp.GetDateTimestamp
user42467 Dec 07 '08 at 23:40 2008-12-07 23:40
source share