如何在 C# 中检测蜂窝连接

How to detect a cellular connection in C#

我正在开发 "regular" C# WPF 应用程序(无 UWP 应用程序),我需要知道我是否在使用蜂窝网络连接。在设备内部使用 SIM 卡或使用手机热点时都可以使用蜂窝网络连接 phone。

我怎样才能做到这一点?

背景: 由于该应用程序可能会下载大量数据,因此我希望用户可以选择是否要避免在蜂窝连接上下载)

其他问题: 我看过 this question and , they're focusing on UWP functionality. Also this one,它只关注连接本身,而不是是否是蜂窝连接。

您可以使用 System.Net.NetworkInformation 来识别您的机器网络适配器。

此外,您可以利用 属性 NetworkInterface.OperationalStatus to filter the adapters that are currently connected and NetworkInterfaceType 来识别连接类型。检查下面的示例。

不幸的是,我的机器上没有蜂窝调制解调器来检查它是否 returns 想要的结果,但请尝试并告诉我们它是否有效。

 NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
 foreach (NetworkInterface adapter in interfaces)
    {
        //Check if it's connected
        if (adapter.OperationalStatus == OperationalStatus.Up
            //The network interface uses a mobile broadband interface for WiMax devices.
            && (adapter.NetworkInterfaceType == NetworkInterfaceType.Wman
                //The network interface uses a mobile broadband interface for GSM-based devices.
                || adapter.NetworkInterfaceType == NetworkInterfaceType.Wwanpp
                //The network interface uses a mobile broadband interface for CDMA-based devices.
                || adapter.NetworkInterfaceType == NetworkInterfaceType.Wwanpp2))
        {
            //adapter probably is cellular
        }                
    }

我试验了 UWP 库并能够使用 UWP 引用解决它。

我添加了这个参考:

C:\Program Files (x86)\Windows Kits\References.0.17763.0\Windows.Foundation.UniversalApiContract.0.0.0\Windows.Foundation.UniversalApiContract.winmd

并使用此代码检查按流量计费的连接:

private void CheckIsMetered()
{
    var profile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
    IsInternetAvailable = profile != null && profile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
    if (IsInternetAvailable)
        IsMetered = profile.GetConnectionCost().NetworkCostType != Windows.Networking.Connectivity.NetworkCostType.Unrestricted;
}

我使用 NetworkStatusChanged 事件重新检查 IsMetered。

CheckIsMetered();
NetworkInformation.NetworkStatusChanged += (s) => CheckIsMetered(); 

这适用于我的 WPF 应用程序。