关闭

C#如何去检测网络的连接状态

发表于:2013-8-26 10:10

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:重做放牛娃    来源:51Testing软件测试网采编

  在有些程序中,你可能希望能检测网络是否连通的,而又不想销耗过多的系统资源,下面的方法是直接调用系统的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. 完整的代码:

using System.Runtime.InteropServices;

namespace internet
{
public class Class1
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( out int connectionDescription, int reservedValue ) ;
public Class1(){}
private bool IsConnected()
{
int I=0;
bool state = InternetGetConnectedState(out I,0);
return state;
}
}

  }

《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号