如何去检测主机网络的连接状态(C#) 收藏

如何去检测网络的连接状态(C#) 收藏
    在有些程序中,你可能希望能检测网络是否连通的,而又不想销耗过多的系统资源,下面的方法是直接调用系统的API去做到检测。

1. 方法定义
  [DllImport("wininet.dll")]
  private extern static bool InternetGetConnectedState( out int connectionDescription, int reservedValue ) ;

2. 方法说明
  参数:
  connectionDescription : 连接说明
  reservedValue : 保留值
  返回值:
   true: On Line
   false: Off Line

3. 调用方法
  a. 你必须在你的code里引用System.Runtime.InteropServices,否则,会有编译错误
  b. 定义一个变量 int I = 0;
  c. 调用bool state = InternetGetConnectedState(out I,0);

4. 完整的代码:

 1 using System.Runtime.InteropServices;
 2   namespace internet
 3   {
 4    public class Class1
 5    {
 6        [DllImport("wininet.dll")]
 7        private extern static bool InternetGetConnectedState( out int connectionDescription, int reservedValue ) ;
 8        public Class1(){}
 9        private bool IsConnected()
10        {    
11            int I=0;
12            bool state = InternetGetConnectedState(out I,0);
13            return state;
14       }
15    }
16   }

 

    

posted @ 2010-03-23 17:03  Lux  阅读(830)  评论(1编辑  收藏  举报