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

2
  • 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 <img> element, spawn another Request. Any different idea ? Commented Aug 15, 2014 at 4:03
  • Possible duplicate of How to check if a file exists on an webserver by its URL? Commented Apr 2, 2019 at 5:33

8 Answers 8

53

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Can this method be applied to folders if they exist or not?
@JL, what folders? filesystem ??
Won't this return true for every file, not just images?
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;
    }
}

3 Comments

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 }
Also if you get any ProtocolError (The remote server returned an error: (500) Internal Server Error.) change: request.Method="GET";
What's the mimeType to be specified for image?
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;
            }
    }

Comments

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";
}

Comments

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.

Comments

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;
}

Comments

1

Check if the file exists in the folder where you store the asset on the website.

System.IO.File.Exists(Server.MapPath("~/img/testimg.jpg"));

Comments

-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

1 Comment

The only thing it will download is the response header, which is by definition the "response"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.