c# 网络是否连接
方案一:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Runtime.InteropServices;//必须引用这个命名空间 namespace NetWorkConn_Demo
{
class Program
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue); static void Main(string[] args)
{
int flag = ;
var isConn = InternetGetConnectedState(out flag, );
if (isConn)
{
Console.WriteLine("网络已连接!");
}
else
{
Console.WriteLine("网络已断开!");
}
Console.ReadKey();
}
}
}
方案二: 【不好】
Ping p = new Ping();
PingReply reply = p.Send("192.168.0.0", 100);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("网络已连接!");
}
else
{
Console.WriteLine("网络已断开!");
}