如何知道MS Windows是否有红色或互联网连接?

时间:2012-07-06 19:15:53

标签: c# .net

  

可能重复:
  check whether internet connection is available with C#

我只是想知道如果MS Windows具有活动的Internet /红色连接或者没有,我们必须使用哪些方法以编程方式(C#)进行检测。

有可能吗?

谢谢!

例如:如果我放下WIFI,我怎么知道有任何连接?

2 个答案:

答案 0 :(得分:2)

查看Ping class

       Ping pingSender = new Ping ();
        PingOptions options = new PingOptions ();

        // Use the default Ttl value which is 128,
        // but change the fragmentation behavior.
        options.DontFragment = true;

        // Create a buffer of 32 bytes of data to be transmitted.
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes (data);
        int timeout = 120;
        PingReply reply = pingSender.Send ("www.google.com", timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {
            Console.WriteLine ("Address: {0}", reply.Address.ToString ());
            Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
            Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
            Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
            Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
        }

答案 1 :(得分:0)

我使用以下方法检查连接性:

public bool CheckForInternetConnection()
    {
        try
        {
            using (var client = new WebClient())
            using (var stream = client.OpenRead("http://www.google.com"))
            {
                Console.WriteLine("You Have connectity!");
                return true;
            }
        }
        catch
        {
            Console.WriteLine("No internet connection found.");
            return false;
        }
    }

该方法尝试加载Google的URL,如果加载则返回true,否则返回false。