In my application I use the WebClient class to download files from a Webserver by simply calling the DownloadFile method. Now I need to check whether a certain file exists prior to downloading it (or in case I just want to make sure that it exists). I've got two questions with that:
- What is the best way to check whether a file exists on a server without transfering to much data across the wire? (It's quite a huge number of files I need to check)
- Is there a way to get the size of a given remote file without downloading it?
Thanks in advance!
WebClient
is fairly limited; if you switch to usingWebRequest
, then you gain the ability to send an HTTP HEAD request. When you issue the request, you should either get an error (if the file is missing), or aWebResponse
with a validContentLength
property.Edit: Example code:
When you request file using the WebClient Class, the 404 Error (File Not Found) will lead to an exception. Best way is to handle that exception and use a flag which can be set to see if the file exists or not.
The example code goes as follows:
You can put your code in respective if blocks. Hope it helps!