Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test to see if an image exists in C#

Tags:

c#

.net

iis

I am writing a diagnostic page for SiteScope and one area we need to test is if the connection to the file/media assets are accesible from the web server. One way I think I can do this is load the image via code behind and test to see if the IIS status message is 200.

So basically I should be able to navigate to within the site to a folder like this: /media/1/image.jpg and see if it returns 200...if not throw exception.

I am struggling to figure out how to write this code.

Any help is greatly appreciated.

Thanks

like image 895
RedWolves Avatar asked Oct 10 '08 16:10

RedWolves


2 Answers

Just use HEAD. No need to download the entire image if you don't need it. Here some boilerplate code.

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url"); request.Method = "HEAD";  bool exists; try {     request.GetResponse();     exists = true; } catch {    exists = false; } 
like image 121
Greg Dean Avatar answered Sep 19 '22 16:09

Greg Dean


You might want to also check that you got an OK status code (ie HTTP 200) and that the mime type from the response object matches what you're expecting. You could extend that along the lines of,

public bool doesImageExistRemotely(string uriToImage, string mimeType) {     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage);     request.Method = "HEAD";      try     {         HttpWebResponse response = (HttpWebResponse)request.GetResponse();          if (response.StatusCode == HttpStatusCode.OK && response.ContentType == mimeType)         {             return true;         }         else         {             return false;         }        }     catch     {         return false;     } } 
like image 23
Anjisan Avatar answered Sep 20 '22 16:09

Anjisan