0

In my winforms app i need to check if the system is connected to internet. Currently I am using

        try
        {
            Dns.GetHostEntry("www.something.com");
            return true;
        }
        catch (Exception)
        {
            return false;
        }

But this doesn't cut it for me. It takes more than two minutes to start the application if the system is not connected to internet(because of Timeout). Was wondering if WMI command can be used instead?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
smons
  • 455
  • 2
  • 6
  • 17

3 Answers3

2

I use This Class For Check Internet Connect if User connect with Dsl Modem , below code Can't Sense Internet Connect

NetworkInterface.GetIsNetworkAvailable()

But This Class Can Solve This ,

class InternetConnectionChecker
{
    private bool _connectingFlag = false;
    private Thread _th;

    #region Ping Google To Test Connect Or Disconnect
    private string Ping()
    {
        try
        {
            const string remoteMachineNameOrIP = "173.194.78.104";
            var ping = new Ping();
            var reply = ping.Send(remoteMachineNameOrIP, 5);
            var sb = new StringBuilder();
            sb.Append(reply.Status.ToString());
            return sb.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
    #endregion

    #region Connecting Cheker Thread
    private void ConCheck()
    {
        var status = Ping();
        _connectingFlag = status == "Success" || status == "TimedOut";
    }

    public bool ConnectingCheker()
    {
        _th = new Thread(ConCheck);
        _th.Start();
        return _connectingFlag;
    }
    #endregion
}

For Use //Dont Forget Create Global Instance InternetConnectionChecker

    InternetConnectionChecker _connectionChecker = new     InternetConnectionChecker();

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {           
        btn1.Content = _connectionChecker.ConnectingCheker();
    }
ali.alikhani
  • 185
  • 1
  • 2
  • 9
0

I don't know about WMI, but there are some .NET Framework classes that can help in the System.Net.NetworkInformation namespace. In particular, NetworkInterface.GetIsNetworkAvailable() can tell you if a network connection (not necessarily with internet) is available. In the same namespace, the Ping class has several methods for send ping requests that are asynchronous and/or have timeout parameters.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
0

I used wininet.dll instead to solve my problem and it works like a charm.

Please reference this link for its usage.

Thanks guys for your time.

smons
  • 455
  • 2
  • 6
  • 17