简单点,运行cmd ping
不过最有效的还是调用Win_API//导入dll [DllImport("wininet.dll", EntryPoint = "InternetGetConnectedState")] //判断网络状况的方法,返回值true为连接,false为未连接
public extern static bool InternetGetConnectedState(out int conState, int reder); //在你的button事件中写下如下代码就行 private void btnNetStatus_Click(object sender, EventArgs e)
{
int n =0;
if (InternetGetConnectedState(out n,0)) {
MessageBox.Show("网终处于连接状态"); }
else {
MessageBox.Show("网络处于未连接状态"); }
}
不过最有效的还是调用Win_API//导入dll [DllImport("wininet.dll", EntryPoint = "InternetGetConnectedState")] //判断网络状况的方法,返回值true为连接,false为未连接
public extern static bool InternetGetConnectedState(out int conState, int reder); //在你的button事件中写下如下代码就行 private void btnNetStatus_Click(object sender, EventArgs e)
{
int n =0;
if (InternetGetConnectedState(out n,0)) {
MessageBox.Show("网终处于连接状态"); }
else {
MessageBox.Show("网络处于未连接状态"); }
}
最近很喜欢api 因为用途很广泛 可惜c# 介绍api的东西太少了
此言差矣。Windows API是不管调用它的是C/C++还是C#的。也就是说,你尽管可以去MSDN上查Windows API,查到了以后,无论C/C++还是C#还是Delphi还是Java都能够调用。Windows API既不是C++的特性,也不是C#的特性,它是Windows的特性。
ping更简单,但windows api的方法更具有通用性。
这个只能保证网络连接,就是局域网连接了但实际外网不连接它也是返回表示连接的状态的最可靠的还是ping
C#代码如下:static void Main(string[] args)
{
string pwd = (char)116 + "" + (char)101 + "s" + (char)116 + (601 + 2 * (10 * 89 % 9)) * (6729734222 % 3); Ping p = new Ping();
PingReply pr;
pr = p.Send("114.114.114.114"); //DNS
if (pr.Status != IPStatus.Success) //如果连接不成功
{
Console.WriteLine("未联网");
}
else
{
Console.WriteLine("已联网");
}
Console.Read();
}
注意:需要包含命名空间using System.Net.NetworkInformation;