28

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

Dana
  • 32,083
  • 17
  • 62
  • 73
RedWolves
  • 10,379
  • 12
  • 49
  • 68
  • What if I want to test a page with URL like `http://localhost/homepage` and see if there is any missing image in this page ? My initial idea is to read the page using `HttpWebRequest`, get the Response then look into the content, for each element, spawn another Request. Any different idea ? – Dio Phung Aug 15 '14 at 04:03
  • Possible duplicate of [How to check if a file exists on an webserver by its URL?](https://stackoverflow.com/questions/1460273/how-to-check-if-a-file-exists-on-an-webserver-by-its-url) – Esko Apr 02 '19 at 05:33

7 Answers7

54

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;
}
Greg Dean
  • 29,221
  • 14
  • 67
  • 78
22

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;
    }
}
VMAtm
  • 27,943
  • 17
  • 79
  • 125
Anjisan
  • 1,789
  • 3
  • 15
  • 26
  • 1
    I would like to add that if you add a using statement around HttpWebResponse request ... you will make sure your app will not hang after three consecutive requests. This scenario may come up when a BackgroundWorker is used. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //the logic comes here } – asuciu Aug 28 '12 at 17:37
  • Also if you get any ProtocolError (The remote server returned an error: (500) Internal Server Error.) change: request.Method="GET"; – asuciu Aug 28 '12 at 18:49
  • 1
    What's the mimeType to be specified for image? – Shimmy Weitzhandler Nov 07 '12 at 16:41
8

You have to dispose of the HTTPWebResponse object, otherwise you will have issues as I have had...

    public bool DoesImageExistRemotely(string uriToImage)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage);

            request.Method = "HEAD";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (WebException) { return false; }
            catch
            {
                return false;
            }
    }
6

I've used something like this before, but there's probably a better way:

try
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://somewhere/picture.jpg");
    request.Credentials = System.Net.CredentialCache.DefaultCredentials;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    myImg.ImageUrl = "http://somewhere/picture.jpg";
}
catch (Exception ex)
{
    // image doesn't exist, set to default picture
    myImg.ImageUrl = "http://somewhere/default.jpg";
}
beno
  • 2,160
  • 1
  • 25
  • 24
1

If url exists like http:\server.myImageSite.com the answer is false too only if imageSize > 0 is true.

  public static void GetPictureSize(string url, ref float width, ref float height, ref string err)
  {
    System.Net.HttpWebRequest wreq;
    System.Net.HttpWebResponse wresp;
    System.IO.Stream mystream;
    System.Drawing.Bitmap bmp;

    bmp = null;
    mystream = null;
    wresp = null;
    try
    {
        wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
        wreq.AllowWriteStreamBuffering = true;

        wresp = (HttpWebResponse)wreq.GetResponse();

        if ((mystream = wresp.GetResponseStream()) != null)
            bmp = new System.Drawing.Bitmap(mystream);
    }
    catch (Exception er)
    {
        err = er.Message;
        return;
    }
    finally
    {
        if (mystream != null)
            mystream.Close();

        if (wresp != null)
            wresp.Close();
    }
    width = bmp.Width;
    height = bmp.Height;
}

public static bool ImageUrlExists(string url)
{

    float width = 0;
    float height = 0;
    string err = null;
    GetPictureSize(url, ref width, ref height, ref err);
    return width > 0;
}
Paulos02
  • 163
  • 1
  • 4
1

If you are getting an exception during the request like "The remote server returned an error: (401) Unauthorized.",

This can be resolved by adding the following line

request.Credentials = new NetworkCredential(username, password);

Question and answer added to this questions from check if image exists on intranet.

Community
  • 1
  • 1
jhamm
  • 1,858
  • 21
  • 19
-1

I'd look into an HttpWebRequest instead - I think the previous answer will actually download data, whereas you should be able to get the response without data from HttpWebRequest.

http://msdn.microsoft.com/en-us/library/456dfw4f.aspx until step #4 should do the trick. There are other fields on HttpWebResponse for getting the numerical code if needs be...

hth Jack

user25519
  • 61
  • 1
  • 4