首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#读取Windows宽带连接属性

C#读取Windows宽带连接属性
EN

Stack Overflow用户
提问于 2013-09-02 16:34:06
回答 4查看 10.2K关注 0票数 8

首先,这里是背景:

我们有一个Windows应用程序(用C#编写,.NET Framework3.5编写),目前运行在Windows 7平板电脑上,其中内置了一个用于数据连接的3G模块。数据连接在Windows中配置为正常的移动宽带连接(因此Windows管理连接本身),连接显示在“控制面板”>“网络”和“Internet >网络连接”中,并且工作良好--应用程序能够通过internet与我们的web服务进行通信。在未来的某个时候,我们将转向另一种设备(可能是一款完整的基于Windows 8的平板电脑)。

现在,我需要做的是读取这个移动宽带连接的连接状态,即获取信号强度和载波名称(例如,沃达丰英国)。我已经找到了一种使用Windows7SDK的Mobile部分(请参阅herehere)来实现这一点的方法,但是这似乎是特定于操作系统的,因为它在Windows 8上不起作用--或者至少对我这里的设备不起作用。

是否有使用.NET框架读取移动宽带连接属性的通用方法?

或者,有人知道Windows8SDK包含一个移动宽带API,就像我目前正在使用的Windows 7那样吗?

提前谢谢。

更新-我已经在一系列不同的Win 7/ Win 8设备上工作。就连联想的设备也能正常工作。我将把主位的示例代码(读取连接状态、配置连接、检查SIM状态)作为答案;代码太长了,无法回答这个问题。

EN

回答 4

Stack Overflow用户

发布于 2013-11-18 16:56:30

以编程方式配置连接(您将需要APN详细信息):

代码语言:javascript
复制
try
        {
            MbnInterfaceManager mbnInfMgr = new MbnInterfaceManager(); 
            IMbnInterfaceManager mbnInfMgrInterface = mbnInfMgr as IMbnInterfaceManager;
            if (mbnInfMgrInterface != null)
            {
                IMbnInterface[] mobileInterfaces = mbnInfMgrInterface.GetInterfaces() as IMbnInterface[];
                if (mobileInterfaces != null && mobileInterfaces.Length > 0)
                {
                    // Just use the first interface
                    IMbnSubscriberInformation subInfo = mobileInterfaces[0].GetSubscriberInformation();

                    if (subInfo != null)
                    {
                        SIMNumber = subInfo.SimIccID;
                        // Get the connection profile
                        MbnConnectionProfileManager mbnConnProfileMgr = new MbnConnectionProfileManager();
                        IMbnConnectionProfileManager mbnConnProfileMgrInterface = mbnConnProfileMgr as IMbnConnectionProfileManager; 
                        if (mbnConnProfileMgrInterface != null)
                        {
                            bool connProfileFound = false;
                            string profileName = String.Empty;

                            try
                            {
                                IMbnConnectionProfile[] mbnConnProfileInterfaces = mbnConnProfileMgrInterface.GetConnectionProfiles(mobileInterfaces[0]) as IMbnConnectionProfile[];

                                foreach (IMbnConnectionProfile profile in mbnConnProfileInterfaces)
                                {
                                    string xmlData = profile.GetProfileXmlData();

                                    if (xmlData.Contains("<SimIccID>" + SIMNumber + "</SimIccID>"))
                                    {
                                        connProfileFound = true;
                                        bool updateRequired = false;

                                        // Check if the profile is set to auto connect
                                        XmlDocument xdoc = new XmlDocument();
                                        xdoc.LoadXml(xmlData);

                                        profileName = xdoc["MBNProfile"]["Name"].InnerText;

                                        if (xdoc["MBNProfile"]["ConnectionMode"].InnerText != "auto")
                                        {
                                            xdoc["MBNProfile"]["ConnectionMode"].InnerText = "auto";
                                            updateRequired = true;
                                        }

                                        // Check the APN settings
                                        if (xdoc["MBNProfile"]["Context"] == null)
                                        {
                                            XmlElement context = (XmlElement)xdoc["MBNProfile"].AppendChild(xdoc.CreateElement("Context", xdoc["MBNProfile"].NamespaceURI));
                                            context.AppendChild(xdoc.CreateElement("AccessString", xdoc["MBNProfile"].NamespaceURI));
                                            context.AppendChild(xdoc.CreateElement("Compression", xdoc["MBNProfile"].NamespaceURI));
                                            context.AppendChild(xdoc.CreateElement("AuthProtocol", xdoc["MBNProfile"].NamespaceURI));
                                            updateRequired = true;
                                        }

                                        if (xdoc["MBNProfile"]["Context"]["AccessString"].InnerText != APNAccessString)
                                        {
                                            xdoc["MBNProfile"]["Context"]["AccessString"].InnerText = APNAccessString;
                                            updateRequired = true;
                                        }
                                        if (xdoc["MBNProfile"]["Context"]["Compression"].InnerText != APNCompression)
                                        {
                                            xdoc["MBNProfile"]["Context"]["Compression"].InnerText = APNCompression;
                                            updateRequired = true;
                                        }
                                        if (xdoc["MBNProfile"]["Context"]["AuthProtocol"].InnerText != APNAuthProtocol)
                                        {
                                            xdoc["MBNProfile"]["Context"]["AuthProtocol"].InnerText = APNAuthProtocol;
                                            updateRequired = true;
                                        }

                                        if (xdoc["MBNProfile"]["Context"]["UserLogonCred"] == null && !String.IsNullOrEmpty(APNUsername))
                                        {
                                            XmlElement userLogonCred = (XmlElement)xdoc["MBNProfile"]["Context"].InsertAfter(xdoc.CreateElement("UserLogonCred", xdoc["MBNProfile"].NamespaceURI), xdoc["MBNProfile"]["Context"]["AccessString"]);
                                            userLogonCred.AppendChild(xdoc.CreateElement("UserName", xdoc["MBNProfile"].NamespaceURI));
                                            userLogonCred.AppendChild(xdoc.CreateElement("Password", xdoc["MBNProfile"].NamespaceURI));
                                            updateRequired = true;
                                        }

                                        if (xdoc["MBNProfile"]["Context"]["UserLogonCred"] != null && xdoc["MBNProfile"]["Context"]["UserLogonCred"]["UserName"].InnerText != APNUsername)
                                        {
                                            xdoc["MBNProfile"]["Context"]["UserLogonCred"]["UserName"].InnerText = APNUsername;
                                            updateRequired = true;
                                        }

                                        if (xdoc["MBNProfile"]["Context"]["UserLogonCred"] != null && xdoc["MBNProfile"]["Context"]["UserLogonCred"]["Password"] == null && !String.IsNullOrEmpty(APNUsername))
                                        {
                                            xdoc["MBNProfile"]["Context"]["UserLogonCred"].AppendChild(xdoc.CreateElement("Password", xdoc["MBNProfile"].NamespaceURI));
                                        }

                                        if (xdoc["MBNProfile"]["Context"]["UserLogonCred"] != null && xdoc["MBNProfile"]["Context"]["UserLogonCred"]["Password"].InnerText != APNPassword)
                                        {
                                            xdoc["MBNProfile"]["Context"]["UserLogonCred"]["Password"].InnerText = APNPassword;
                                            updateRequired = true;
                                        }

                                        if (updateRequired)
                                        {
                                            // Update the connection profile
                                            profile.UpdateProfile(xdoc.OuterXml);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                if (!ex.Message.Contains("Element not found"))
                                {
                                    throw ex;
                                }
                            }

                            if (!connProfileFound)
                            {
                                // Create the connection profile
                                XmlDocument xdoc = new XmlDocument();
                                xdoc.AppendChild(xdoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
                                XmlElement mbnProfile = (XmlElement)xdoc.AppendChild(xdoc.CreateElement("MBNProfile", "http://www.microsoft.com/networking/WWAN/profile/v1"));
                                mbnProfile.AppendChild(xdoc.CreateElement("Name", xdoc["MBNProfile"].NamespaceURI)).InnerText = SIMNumber;
                                mbnProfile.AppendChild(xdoc.CreateElement("IsDefault", xdoc["MBNProfile"].NamespaceURI)).InnerText = "true";
                                mbnProfile.AppendChild(xdoc.CreateElement("ProfileCreationType", xdoc["MBNProfile"].NamespaceURI)).InnerText = "DeviceProvisioned";
                                mbnProfile.AppendChild(xdoc.CreateElement("SubscriberID", xdoc["MBNProfile"].NamespaceURI)).InnerText = subInfo.SubscriberID;
                                mbnProfile.AppendChild(xdoc.CreateElement("SimIccID", xdoc["MBNProfile"].NamespaceURI)).InnerText = SIMNumber;
                                mbnProfile.AppendChild(xdoc.CreateElement("HomeProviderName", xdoc["MBNProfile"].NamespaceURI)).InnerText = SIMNumber;
                                mbnProfile.AppendChild(xdoc.CreateElement("AutoConnectOnInternet", xdoc["MBNProfile"].NamespaceURI)).InnerText = "true";
                                mbnProfile.AppendChild(xdoc.CreateElement("ConnectionMode", xdoc["MBNProfile"].NamespaceURI)).InnerText = "auto";

                                XmlElement context = (XmlElement)xdoc["MBNProfile"].AppendChild(xdoc.CreateElement("Context", xdoc["MBNProfile"].NamespaceURI));
                                context.AppendChild(xdoc.CreateElement("AccessString", xdoc["MBNProfile"].NamespaceURI));
                                XmlElement userLogonCred = (XmlElement)context.AppendChild(xdoc.CreateElement("UserLogonCred", xdoc["MBNProfile"].NamespaceURI));
                                userLogonCred.AppendChild(xdoc.CreateElement("UserName", xdoc["MBNProfile"].NamespaceURI));
                                userLogonCred.AppendChild(xdoc.CreateElement("Password", xdoc["MBNProfile"].NamespaceURI));
                                context.AppendChild(xdoc.CreateElement("Compression", xdoc["MBNProfile"].NamespaceURI));
                                context.AppendChild(xdoc.CreateElement("AuthProtocol", xdoc["MBNProfile"].NamespaceURI));

                                xdoc["MBNProfile"]["Context"]["AccessString"].InnerText = APNAccessString;
                                xdoc["MBNProfile"]["Context"]["UserLogonCred"]["UserName"].InnerText = APNUsername;
                                xdoc["MBNProfile"]["Context"]["UserLogonCred"]["Password"].InnerText = APNPassword;
                                xdoc["MBNProfile"]["Context"]["Compression"].InnerText = APNCompression;
                                xdoc["MBNProfile"]["Context"]["AuthProtocol"].InnerText = APNAuthProtocol;

                                profileName = xdoc["MBNProfile"]["Name"].InnerText;

                                mbnConnProfileMgrInterface.CreateConnectionProfile(xdoc.OuterXml); 
                            }

                            // Register the connection events
                            MbnConnectionManager connMgr = new MbnConnectionManager();
                            IConnectionPointContainer connPointContainer = connMgr as IConnectionPointContainer;

                            Guid IID_IMbnConnectionEvents = typeof(IMbnConnectionEvents).GUID;
                            IConnectionPoint connPoint;
                            connPointContainer.FindConnectionPoint(ref IID_IMbnConnectionEvents, out connPoint);

                            ConnectionEventsSink connEventsSink = new ConnectionEventsSink();
                            connPoint.Advise(connEventsSink, out cookie); if (showProgress) { MessageBox.Show("After registering events"); }

                            // Connect
                            IMbnConnection connection = mobileInterfaces[0].GetConnection();

                            if (connection != null)
                            {
                                MBN_ACTIVATION_STATE state;
                                string connectionProfileName = String.Empty;
                                connection.GetConnectionState(out state, out connectionProfileName);

                                if (state != MBN_ACTIVATION_STATE.MBN_ACTIVATION_STATE_ACTIVATED && state != MBN_ACTIVATION_STATE.MBN_ACTIVATION_STATE_ACTIVATING)
                                {
                                    if (String.IsNullOrEmpty(connectionProfileName))
                                    {
                                        connectionProfileName = profileName;
                                    }
                                    uint requestID;
                                    connection.Connect(MBN_CONNECTION_MODE.MBN_CONNECTION_MODE_PROFILE, connectionProfileName, out requestID);

                                }
                                else
                                {
                                    // Do nothing, already connected
                                }
                            }
                            else
                            {
                                MessageBox.Show("Connection not found.");
                            }
                        }
                        else
                        {
                            MessageBox.Show("mbnConnProfileMgrInterface is null.");
                        }
                    }
                    else
                    {
                        MessageBox.Show("No subscriber info found.");
                    }
                }
                else
                {
                    MessageBox.Show("No mobile interfaces found.");
                }
            }
            else
            {
                MessageBox.Show("mbnInfMgrInterface is null.");
            }
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("SIM is not inserted."))
            {
                SIMNumber = "No SIM inserted.";
            }
            MessageBox.Show("LoginForm.DataConnection ConfigureWindowsDataConnection Error " + ex.Message);
        }
票数 4
EN

Stack Overflow用户

发布于 2013-11-18 15:50:21

读取连接状态

代码语言:javascript
复制
try
        {
            MbnInterfaceManager mbnInfMgr = new MbnInterfaceManager();
            IMbnInterfaceManager mbnInfMgrInterface = mbnInfMgr as IMbnInterfaceManager;
            if (mbnInfMgrInterface != null)
            {
                IMbnInterface[] mobileInterfaces = mbnInfMgrInterface.GetInterfaces() as IMbnInterface[];
                if (mobileInterfaces != null && mobileInterfaces.Length > 0)
                {
                    // Use the first interface, as there should only be one mobile data adapter
                    IMbnSignal signalDetails = mobileInterfaces[0] as IMbnSignal;

                    Int32.TryParse(signalDetails.GetSignalStrength().ToString(), out PhoneSignal);
                    PhoneSignal = Convert.ToInt32(((float)PhoneSignal / 16) * 100);

                    MBN_PROVIDER provider = mobileInterfaces[0].GetHomeProvider();
                    PhoneNetwork = provider.providerName.ToString();

                    if (String.IsNullOrEmpty(SIMNumber))
                    {
                        try
                        {
                            IMbnSubscriberInformation subInfo = mobileInterfaces[0].GetSubscriberInformation();

                            if (subInfo != null)
                            {
                                SIMNumber = subInfo.SimIccID;
                            }
                            else
                            {
                                SIMNumber = "Unable to read SIM info";
                            }
                        }
                        catch (Exception)
                        {
                            SIMNumber = "Unable to read SIM info";
                        }
                    }

                    // Check whether the connection is active
                    IMbnConnection connection = mobileInterfaces[0].GetConnection();

                    if (connection != null)
                    {
                        MBN_ACTIVATION_STATE state;
                        string profileName = String.Empty;
                        connection.GetConnectionState(out state, out profileName);

                        Connected = (state == MBN_ACTIVATION_STATE.MBN_ACTIVATION_STATE_ACTIVATED);
                    }
                    else
                    {
                        MessageBox.Show("Connection not found.");
                    }
                }
                else
                {
                    MessageBox.Show("No mobile interfaces found.");
                }
            }
            else
            {
                MessageBox.Show("mbnInfMgrInterface is null.");
            }
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("SIM is not inserted."))
            {
                SIMNumber = "No SIM inserted.";
            }
            else
            {
                MessageBox.Show("LoginForm.DataConnection GetWindowsMobileDataStatus " + ex.Message);
            }
            PhoneSignal = 0;
            PhoneNetwork = "Unknown";
        }
票数 3
EN

Stack Overflow用户

发布于 2013-11-18 15:54:07

插入检查SIM并工作/激活

代码语言:javascript
复制
try
        {
            MbnInterfaceManager mbnInfMgr = new MbnInterfaceManager();
            IMbnInterfaceManager mbnInfMgrInterface = mbnInfMgr as IMbnInterfaceManager;
            if (mbnInfMgrInterface != null)
            {
                IMbnInterface[] mobileInterfaces = mbnInfMgrInterface.GetInterfaces() as IMbnInterface[];
                if (mobileInterfaces != null && mobileInterfaces.Length > 0)
                {
                    try
                    {
                        MBN_READY_STATE readyState = mobileInterfaces[0].GetReadyState();

                        switch (readyState)
                        {
                            case MBN_READY_STATE.MBN_READY_STATE_BAD_SIM:
                                MessageBox.Show("The SIM is invalid (PIN Unblock Key retrials have exceeded the limit).");
                                break;
                            case MBN_READY_STATE.MBN_READY_STATE_DEVICE_BLOCKED:
                                MessageBox.Show("The device is blocked by a PIN or password which is preventing the device from initializing and registering onto the network.");
                                break;
                            case MBN_READY_STATE.MBN_READY_STATE_DEVICE_LOCKED:
                                MessageBox.Show("The device is locked by a PIN or password which is preventing the device from initializing and registering onto the network.");
                                break;
                            case MBN_READY_STATE.MBN_READY_STATE_FAILURE:
                                MessageBox.Show("General device failure.");
                                break;
                            case MBN_READY_STATE.MBN_READY_STATE_INITIALIZED:
                                try
                                {
                                    IMbnSubscriberInformation subInfo = mobileInterfaces[0].GetSubscriberInformation();

                                    if (subInfo != null)
                                    {
                                        SIMNumber = subInfo.SimIccID;
                                    }
                                    else
                                    {
                                        SIMNumber = "Unable to read SIM info";
                                    }
                                }
                                catch (Exception)
                                {
                                    SIMNumber = "Unable to read SIM info";
                                }

                                IMbnRegistration registration = mobileInterfaces[0] as IMbnRegistration;
                                if (registration != null)
                                {
                                    try
                                    {
                                        MBN_REGISTER_STATE regState = registration.GetRegisterState();

                                        switch (regState)
                                        {
                                            case MBN_REGISTER_STATE.MBN_REGISTER_STATE_DENIED:
                                                // SIM Inactive
                                                simInactive = true;
                                                MessageBox.Show("The device was denied registration. The most likely cause of this error is an Inactive SIM.");
                                                break;
                                            case MBN_REGISTER_STATE.MBN_REGISTER_STATE_DEREGISTERED:
                                                // Do nothing - this is returned before the device has tried to register
                                                break;
                                            case MBN_REGISTER_STATE.MBN_REGISTER_STATE_HOME:
                                                // Do nothing
                                                break;
                                            case MBN_REGISTER_STATE.MBN_REGISTER_STATE_NONE:
                                                MessageBox.Show("The device registration state is unknown. This state may be set upon failure of registration mode change requests.");
                                                break;
                                            case MBN_REGISTER_STATE.MBN_REGISTER_STATE_PARTNER:
                                                // Do nothing
                                                break;
                                            case MBN_REGISTER_STATE.MBN_REGISTER_STATE_ROAMING:
                                                // Do nothing
                                                break;
                                            case MBN_REGISTER_STATE.MBN_REGISTER_STATE_SEARCHING:
                                                // Do nothing
                                                break;
                                            default:
                                                MessageBox.Show("GetRegisterState returned an unexpected state: " + regState.ToString());
                                                break;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show("GetRegisterState Error: " + ex.Message);
                                    }
                                }
                                break;
                            case MBN_READY_STATE.MBN_READY_STATE_NOT_ACTIVATED:
                                MessageBox.Show("The subscription is not activated.");
                                break;
                            case MBN_READY_STATE.MBN_READY_STATE_OFF:
                                MessageBox.Show("The mobile broadband device stack is off.");
                                break;
                            case MBN_READY_STATE.MBN_READY_STATE_SIM_NOT_INSERTED:
                                MessageBox.Show("The SIM is not inserted.");
                                break;
                            default:
                                MessageBox.Show("GetReadyState returned an unexpected state: " + readyState.ToString());
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("GetReadyState Error: " + ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("No mobileInterfaces found.");
                }
            }
            else
            {
                MessageBox.Show("mbnInfMgrInterface is null.");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18577510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档