c# - 使用 C# 检查 Internet 连接是否可用

标签 c# windows-7

以编程方式检查互联网连接是否可用的最简单方法是什么?

编辑: 按照建议,我尝试使用以下方法,但它总是返回 true。

[Flags]
enum InternetConnectionState : int
{
    INTERNET_CONNECTION_MODEM = 0x1,
    INTERNET_CONNECTION_LAN = 0x2,
    INTERNET_CONNECTION_PROXY = 0x4,
    INTERNET_RAS_INSTALLED = 0x10,
    INTERNET_CONNECTION_OFFLINE = 0x20,
    INTERNET_CONNECTION_CONFIGURED = 0x40
}

class Program
{
    [DllImport("WININET", CharSet = CharSet.Auto)]
    static extern bool InternetGetConnectedState(ref InternetConnectionState lpdwFlags, int dwReserved);

static void Main(string[] args)
{
    InternetConnectionState flags = 0;
    bool isConnected = InternetGetConnectedState(ref flags, 0);
    Console.WriteLine(isConnected);
    //Console.WriteLine(flags);
    Console.ReadKey();
}
}

其他信息(如果有帮助):我通过共享 wifi 网络访问互联网。

最佳答案

Here是您可以调用的 Windows API。它位于 wininet.dll 中,名为 InternetGetConnectedState .

using System;
using System.Runtime;
using System.Runtime.InteropServices;

public class InternetCS
{
    //Creating the extern function...
    [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState( out int Description, int ReservedValue );

    //Creating a function that uses the API function...
    public static bool IsConnectedToInternet( )
    {
        int Desc ;
        return InternetGetConnectedState( out Desc, 0 ) ;
    }
}

关于c# - 使用 C# 检查 Internet 连接是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1085045/

相关文章:

c# - 如何从 Function App 指定 Azure Key Vault Secret 的属性?

c# - 针对接口(interface)编程而不是实现混淆

c# - 如何使用 switch case 处理异常

windows-7 - Windows 7 - 以编程方式配置应用程序以在 XP 兼容模式下运行

c# - Windows 7 : A generic error occurred in GDI+ 中的编译器问题

c# - 如何在 Asp.Net MVC 2 中通过 JQuery 调用重载的 C# 函数

c# - 在没有 web.config 的情况下使用 log4net

c++ - Windows 7 上的 DirectX 11.2 开发

c++ - 如何让 CMenu 弹出菜单消失?

windows - 计划任务不运行批处理文件