获取MAC地址C# [英] Getting MAC Address C#

查看:130
本文介绍了获取MAC地址C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这code得到一个MAC地址,但它返回一个长字符串,并且不包括':'。

I have found this code to get a MAC address, but it returns a long string and doesn't include ':'.

是否有可能在加':'或分割字符串,并将其添加它自己

Is it possible to add in the ':' or split up the string and add it it myself?

这里是code:

private object GetMACAddress()
{
    string macAddresses = "";

    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
        {
            macAddresses += nic.GetPhysicalAddress().ToString();
            break;
        }
    }

    return macAddresses;
 }

E0:EE:

而我希望它像00显示的东西,它返回的00E0EE00EE00值00:EE:00

It returns the value of 00E0EE00EE00 whereas I want it to display something like 00:E0:EE:00:EE:00.

任何想法?

感谢。

推荐答案

我用下面的code格式来访问的MAC地址你想要的:

i am using following code to access mac address in format you want :

public string GetSystemMACID()
        {
            string systemName = System.Windows.Forms.SystemInformation.ComputerName;
            try
            {
                ManagementScope theScope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
                ObjectQuery theQuery = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
                ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
                ManagementObjectCollection theCollectionOfResults = theSearcher.Get();

                foreach (ManagementObject theCurrentObject in theCollectionOfResults)
                {
                    if (theCurrentObject["MACAddress"] != null)
                    {
                        string macAdd = theCurrentObject["MACAddress"].ToString();
                        return macAdd.Replace(':', '-');
                    }
                }
            }
            catch (ManagementException e)
            {
                           }
            catch (System.UnauthorizedAccessException e)
            {

            }
            return string.Empty;
        }

这篇关于获取MAC地址C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆