Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Check url exist?

Tags:

c#

How can I check whether a page exists at a given URL?

I have this code:

private void check(string path)
    {

        try
        {
            Uri uri = new Uri(path);
            WebRequest request = WebRequest.Create(uri);
            request.Timeout = 3000;
            WebResponse response;
            response = request.GetResponse();

        }
        catch(Exception loi) { MessageBox.Show(loi.Message); }

    }

But that gives an error message about the proxy. :(

like image 558
microstar Avatar asked Mar 07 '10 02:03

microstar


3 Answers

First, you need to understand that your question is at least twofold, you must first check if the server is responsive, using ping for example - that's the first check, while doing this, consider timeout, for which timeout you will consider a page as not existing?

second, try retrieving the page using many methods which are available on google, again, you need to consider the timeout, if the server taking long to replay, the page might still "be there" but the server is just under tons of pressure.

like image 163
MindFold Avatar answered Oct 14 '22 11:10

MindFold


If the proxy needs to authenticate you with your Windows credentials (e.g. you are in a corporate network) use:

WebRequest request=WebRequest.Create(url);
request.UseDefaultCredentials=true;
request.Proxy.Credentials=request.Credentials;
like image 32
laktak Avatar answered Oct 14 '22 12:10

laktak


try
{
    Uri uri = new Uri(path);
    HttpWebRequest request = HttpWebRequest.Create(uri);
    request.Timeout = 3000;
    HttpWebResponse response;
    response = request.GetResponse();
    if (response.StatusCode.Equals(200))
    {
        // great - something is there
    }
}
catch (Exception loi) 
{ 
    MessageBox.Show(loi.Message); 
}

You can check the content-type and length, see MSDN HTTPWebResponse.

like image 33
mo. Avatar answered Oct 14 '22 12:10

mo.