How can I check if an Image exists at http://someurl/myimage.jpg in C#/ASP.NET
It seems like there ought to be a method to check for this — but I cannot find one.
I found this, but it doesn’t really answer the question.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This code should work:
private static bool UrlExists(string url)
{
try
{
new System.Net.WebClient().DownloadData(url);
return true;
}
catch (System.Net.WebException e)
{
if (((System.Net.HttpWebResponse)e.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
return false;
else
throw;
}
}
Method 2
You could try using System.Net.WebRequest to send a ‘HEAD” request to that to the url and check the response to see if the file exists – this should do the job without atually trying to download it.
Method 3
string fileextension = Path.GetExtension(filename);
if (fileextension.ToLower() == ".png" || fileextension.ToLower() == ".jpg" || fileextension.ToLower() == ".jpeg" || fileextension.ToLower() == ".gif" || fileextension.ToLower() == ".bmp"){}
Method 4
Maybe this or this might help. I don’t think there’s a direct command for images, but you could try using the FileExist method.
Method 5
You could use a System.Net.WebClient.DownloadFile function to try to load the image from the URL and see if you get an error. (Most likely a 404 Not Found error)
Its about the only way to do it from a URL. The System.IO namespace and all the functions in there are intended for files on a local machine or a network, so they would be useless to you in this situation.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0