URL in C# Windows form project

T

Tom Spink

Jason said:
Hi,


In my C# Windows form project, I want to verify that if a file
http://myip/myfile.doc exists, how am I supposed to do? (the myip is a
specific public IP)
Thanks for help.


Jason

Hi Jason,

You can use an HttpWebRequest object, and check to see if you get a '404'
back:

///
public bool CheckUrl ( string url )
{
HttpWebRequest wr = (HttpWebRequest) HttpWebRequest.Create( url );

wr.MaximumAutomaticRedirections = 4;
wr.MaximumResponseHeadersLength = 4;
wr.Credentials = CredentialCache.DefaultCredentials;

try
{
webRequest.GetResponse();
}
catch ( WebException )
{
return false;
}

return true;
}
///
 
N

Nicholas Paldino [.NET/C# MVP]

It should be noted that the MaximumAutomaticRedirections and
MaximumResponseHeadersLength properties are not required for this.

Also, it is not disposing of the WebResponse properly.

On top of that, you are not checking the HttpStatusCode property on the
HttpWebResponse to see if you get a valid return code.

Finally, I would use the HEAD HTTP method to make the request (assuming
it supports HTTP 1.1). This way, only the headers are returned, but not the
body. This way, the server does not waste resources sending the document
back (nor do you waste resources having them sent to you).

My code would be this:

public bool CheckUri(string uri)
{
// Get the request.
WebRequest request = WebRequest.Create(url);

// Set the method to "HEAD".
request.Method = "HEAD";

// Wrap in a try/catch.
try
{
// Get the response.
using (HttpWebResponse response = (HttpWebResponse)
request.GetResponse())
{
// Check the status code. This is the most common status code
// but you might want to check others based on your needs.
if (response.HttpStatusCode != HttpStatusCode.OK)
{
// Return false.
return false;
}
}
}
catch (WebException e)
{
// Return false.
return false;
}

return true;
}

Hope this helps.
 
T

Tom Spink

Nicholas said:
It should be noted that the MaximumAutomaticRedirections and
MaximumResponseHeadersLength properties are not required for this.

Also, it is not disposing of the WebResponse properly.

On top of that, you are not checking the HttpStatusCode property on
the
HttpWebResponse to see if you get a valid return code.

Finally, I would use the HEAD HTTP method to make the request
(assuming
it supports HTTP 1.1). This way, only the headers are returned, but not
the
body. This way, the server does not waste resources sending the document
back (nor do you waste resources having them sent to you).
<snippedy-doo-dah>

Well, I didn't write a complete program. But I took most of that code from
MSDN, because I've never used an HttpWebRe<sponse/quest> object before.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top