- I want to check whether the file in an url entered exists or not in .net
- How can I check if an Image exists at http://someurl/myimage.jpg in C#/ASP.NET
So I took the best of both of these posts and created the following helper method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static bool UrlExists(string url) | |
{ | |
try | |
{ | |
var request = WebRequest.Create(url) as HttpWebRequest; | |
if (request == null) return false; | |
request.Method = "HEAD"; | |
using (var response = (HttpWebResponse)request.GetResponse()) | |
{ | |
return response.StatusCode == HttpStatusCode.OK; | |
} | |
} | |
catch (UriFormatException) | |
{ | |
//Invalid Url | |
return false; | |
} | |
catch (WebException) | |
{ | |
//Unable to access url | |
return false; | |
} | |
} |
Please feel free to modify this if you find any issues or problems with.
3 comments:
Doesn't work.....
Property or indexer 'System.Net.HttpWebResponse.StatusCode' cannot be assigned to -- it is read only!
Thanks for catching that I was missing an additional equals sign. I am not trying to assign to the HttpWebResponse.StatusCode property, just compare it to HttpStatusCiode.Ok
The code has now been updated.
I would rather catching all exceptions and inside the catch, doing a retry using GET instead. Because some servers doesn´t allow HEAD as request method. Try for instance http://www.amazon.com.
Post a Comment