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?
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?
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:
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.
FtpWebRequest
(nor any other class in .NET) does not have any explicit method to check a file existence. You need to abuse a request likeGetFileSize
orGetDateTimestamp
.If you want a more straightforward code, use some 3rd party FTP library.
For example with WinSCP .NET assembly, you can use its
Session.FileExists
method:(I'm the author of WinSCP)
I use FTPStatusCode.FileActionOK to check if file exists...
then, in the "else" section, return false.
Because
may fails in some case (550: SIZE not allowed in ASCII mode), you can just check Timestamp instead.