none
C# 如何查看网络名称 RRS feed

答案

  • 你好:

    .NET Framework中本身提供的System.Net.NetworkInformation命名空间提供了一些类,通过这些类可以访问到计算机的网卡信息。参考一下这篇MSDN文档:

    http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.networkinterfacetype(v=vs.110).aspx

    另外借助WMI的帮助也可以获取到活动网络的属性,参考这段代码:

    static void Main(string[] args)
            {
                string wmiMacAddress = string.Empty;
                string networkInterfaceName = string.Empty;
                string interfaceType = string.Empty;
    
                wmiMacAddress = GetMacAddress().Replace(":", "");
                //Get collection of all network interfaces on the given machine.
                NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                for (int i = 0; i < nics.Length; i++)
                {
                    //Compare the network interface's MAC address with the one found using WMI
                    //and append upon succesion.
    
                    if (nics[i].GetPhysicalAddress().ToString().Equals(wmiMacAddress))
                    {
                        networkInterfaceName = nics[i].Description;
                        interfaceType = nics[i].NetworkInterfaceType.ToString();
                    }
                }
                Console.WriteLine("Active Network Interface: {0}, type:{1}", networkInterfaceName, interfaceType);
    
                Console.Read();
            }
    
            static string GetMacAddress()
            {
                //Get list of all Win32_NetworkAdapter objects.
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
                ManagementObjectCollection collection = searcher.Get();
                //--
                //Iterate through results until the property 'MacAddress' is found.
                foreach (ManagementObject obj in collection)
                {
                    if (obj.Properties["MacAddress"] != null)
                    {
                        try
                        {
                            string value = obj.Properties["MacAddress"].Value.ToString();
                            return value;
                        }
                        catch (NullReferenceException) { }
                    }
    
                }
                //--
                return "";
            }
    当你的计算机连接到工作网络的时候,网络共享中心会自动检测。


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2014年7月9日 5:55
    版主