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);完整的代码:
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;
}
}
}
[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);完整的代码:
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;
}
}
}
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
string pingrst;
p.Start();
p.StandardInput.WriteLine("ping -n 1 "+strIp);
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
if(strRst.IndexOf("(0% loss)")!=-1)
pingrst = "连接";
else if( strRst.IndexOf("Destination host unreachable.")!=-1)
pingrst = "无法到达目的主机";
else if(strRst.IndexOf("Request timed out.")!=-1)
pingrst = "超时";
else if(strRst.IndexOf("Unknown host")!=-1)
pingrst = "无法解析主机";
else
pingrst = strRst;
p.Close();
return pingrst; }
楼上的,是 using System.Diagnostics吧。
你的代码确实是一个检测网络连通的方法,但使用我的方法有以下好处:
1. 性能最佳,因为它调用的是windows的API
2. 准确性高
3. 是同步执行的