How to test if Webbrowser gets a connection error when navigating to a new URL?

帅比萌擦擦* 提交于 2019-12-24 01:45:24

问题


I have a PC that loses the Internet connection every 5 minutes. (long to explain why).
On the background I'm running a C# timer every 10 mins that does very simple stuff:

WebBrowser bobo = new WebBrowser();
bobo.Navigate(url);
while(bobo.ReadyState != WebBrowserReadyState.Complete){Application.DoEvents();}
string responsestring = bobo.DocumentText.ToString();
bobo.Dispose();
// and then do some stuff with responsestring

It is very important to make sure that bobo webbrowser DID have an Internet connection when it was loading the page. How do I do that?

I tried "try-catch" statement, but it does not throw exceptions when there is no Internet.

I thought of doing the "loading complete" handler, but it will make my program very complex and use too much memory, so looking for other ways.

My latest solution is:

...
while(bobo.ReadyState != WebBrowserReadyState.Complete){Application.DoEvents();}
if (bobo.DocumentTitle == "Navigation Canceled"){throw new DivideByZeroException();}
...

It works fine for bobo browser. But when I work with responsestring - I create many other browsers (one by one) - and this solution does not work there.

Is there some other kind of test that I did not mention?

Solution found:
Thanks a lot.
I did not use your solution (it returns TRUE few seconds after connection is turned off).
But I found this:

[DllImport("wininet.dll", SetLastError = true)]
static extern bool InternetCheckConnection(string lpszUrl, int dwFlags, int dwReserved);
public static bool CanConnectToURL(string url)
{
return InternetCheckConnection(url, 1, 0);
}

It literally sends a PING to the URL, and returns TRUE if answer is received, otherwise it returns FALSE. Works perfect.


回答1:


From: check whether Internet connection is available with C#

using System;
using System.Runtime;
using System.Runtime.InteropServices;

public class InternetCS
{
//Creating the extern function...
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( out int Description, int ReservedValue );

//Creating a function that uses the API function...
public static bool IsConnectedToInternet( )
{
    int Desc ;
    return InternetGetConnectedState( out Desc, 0 ) ;
}
}

You could also ping your ISP's DNS servers and see if you can reach them, someone on SO said that Windows pings microsoft.com to see if your internet is up.



来源:https://stackoverflow.com/questions/12014295/how-to-test-if-webbrowser-gets-a-connection-error-when-navigating-to-a-new-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!