Link Validation

  • Thread starter Thread starter Darren
  • Start date Start date
D

Darren

Is there a way to determine a link to a file is valid (exists)?

I have found examples using httprequest, but I don't want to retrieve the
entire file, just verify it's existence.
These examples work very well when a link does not exist. But not so much on
valid ones. The files these links point to can be quite large in some cases
making such functions useless if the entire thing must be retrieved.

Thanks
 
Hi,

Try this

System.IO.FileInfo fileInfo = new System.IO.FileInfo("File Path");
if (fileInfo.Exists)
{
// Do this
}
else
{
// Do this
}
 
Sending a HEAD request than a GET request should allow to get the header
rather than the whole content...
 
Darren,

How do you send a HEAD request than a GET
Can you Please share a small example.

Thank you,
 
He is talking about URLs


Ujval Shah said:
Hi,

Try this

System.IO.FileInfo fileInfo = new System.IO.FileInfo("File Path");
if (fileInfo.Exists)
{
// Do this
}
else
{
// Do this
}
 
Is there a way to determine a link to a file is valid (exists)?

I have found examples using httprequest, but I don't want to retrieve the
entire file, just verify it's existence.
These examples work very well when a link does not exist. But not so much on
valid ones. The files these links point to can be quite large in some cases
making such functions useless if the entire thing must be retrieved.

Thanks

Try setting the Method property to "HEAD" ... the web server will be
instructed not to send the entire body
 
How/Where do you set the Method property to "HEAD"
some details please, thank you,

No problem.

Here we go. I wrote a small console application. You will need to add
references to System.Net and System.Web, as well as (System.IO) if you
want to retrieve the actual content

WebRequest r=null;
WebResponse res=null;
try{
r = HttpWebRequest.Create("http://thesiteiwanttocheck.com");
r.Method="HEAD";
res = r.GetResponse();
}
catch(WebException ex){
Console.WriteLine(ex.Status);
}
finally{
if(res!=null)
res.Close();
}

If the site cannot be accessed, a web exception could be thrown. You
can interrogate the status property to discover why. It could be a
problem from your end e.g. proxy authentication, etc or it could be
something wrong with the site. Check the status property before you
flag the site as unavailable!

Unless you say otherwise, the default method used by a HttpWebRequest
is GET. So before we get the response, we set the method as
appropriate.

To prove that the full body is not being retrieved, add the following
code just after GetResponse()

StreamReader sr = new StreamReader(res.GetResponseStream());
Console.Write(sr.ReadToEnd());

Then toggle the Method property between HEAD and GET and see what
happens.

Hope that helps
 
Rad,

Excellent and Thank YOU so much for the detailed code, Now I know what you
are saying.

It definitely helped me out.
 
Back
Top