2

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.

John Smith
  • 891
  • 1
  • 11
  • 17
  • There is no such thing as a "C# WebBrowser". There is a Windows Forms WebBrowser control, and one for WPF. Which one are you asking about? – John Saunders Aug 17 '12 at 23:55

1 Answers1

0

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.

Community
  • 1
  • 1
0_______0
  • 547
  • 3
  • 11