检查Internet连接状态

问题描述:

我想通过c#检查Internet连接.我的计算机已与Network连接,仅Internet禁用.如何查找Internet连接状态.
以下代码不适合我的要求.即使仅连接了网络且已禁用Internet,它也会返回true.

I want to check the internet connectivity thro c#.My computer is connected with Network only internet is disabled.How do i find the internet connectivity status.
The following code is not suitable for my requirement.it returns true even only network is connected and internet disabled.

[DllImport("wininet.dll")]
  private extern static bool InternetGetConnectedState( out int Description, int ReservedValue );
  public static bool IsConnectedToInternet( )
  {
    int Desc ;
    return InternetGetConnectedState( out Desc, 0 ) ;
  }



此(以下)代码有效,但会花费更多时间并使我的应用程序挂起,



This(following) code works but takes more time and makes my application hangs,

System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://www.google.com");
                req.Method = "HEAD";

                System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse();
                resp.Close(); return true;



还有其他检查互联网连接状态的好方法.



Is any other good way to check internet connectivity status.
All your Suggestions are appreciable!!!

如果您使用的是.net 4,请使用Ping以及8.8.8.8(Google的DNS) )
http://msdn.microsoft.com/en-us/library/system. net.networkinformation.ping.aspx [ ^ ]
If you are using .net 4, use Ping and an internet address like : 8.8.8.8 (Google''s DNS)
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx[^]


在使用第二种方法或Mehdi Gholam提供的解决方案时,您可能需要确保从某个线程执行此操作.不是您的主线程,因为这会导致UI挂起.
When using the second approach or the solution provided by Mehdi Gholam, you may want to make sure that you are doing this from a thread that is not your main thread since this would cause the UI to hang.


请参阅以下

http://www.c-sharpcorner.com/UploadFile/scottlysle/ConnectionState02092007002002552AM/ConnectionState.aspx [ ^ ]

http://stackoverflow.com/questions/5405895/how- to-check-internet-connection-with-net-c-wpf [
see these

http://www.c-sharpcorner.com/UploadFile/scottlysle/ConnectionState02092007002552AM/ConnectionState.aspx[^]

http://stackoverflow.com/questions/5405895/how-to-check-internet-connection-with-net-c-wpf[^]