tags:

views:

2653

answers:

5

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

+11  A: 

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
this worked perfectly, thanks.
RedWolves
Can this method be applied to folders if they exist or not?
JL
@JL, what folders? filesystem ??
alhambraeidos
A: 

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

The only thing it will download is the response header, which is by definition the "response"
Greg Dean
+1  A: 

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
+4  A: 
Anjisan
+2  A: 

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;
            }
    }
What issues did you have?
s_hewitt
What issues, mister ?
alhambraeidos