Click here to Skip to main content
15,922,155 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello sir

Please help me in these two issues

1. Below code shows mac address in XP but empty string in Windows7.
2. Is there any chance to find mac address directly with a query instead of looping "foreach" statement.



string MACAddress = String.Empty;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();                
                foreach (ManagementObject mo in moc)
                {
                    if (MACAddress == String.Empty) // only return MAC Address from first card  
                    {
                        if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
                    }
                    mo.Dispose();
                }

                MACAddress = MACAddress.Replace(":", "");
                return MACAddress;
Posted

Check this out

C#
/// <summary>
/// returns the mac address of the first operation nic found.
/// </summary>
/// <returns></returns>
private string GetMacAddress()
{
    string macAddresses = "";

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


More info here:
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.aspx[^]

Cheers!
 
Share this answer
 
v2
dear sir thanks for the reply.

i got the mac address when the cable is plugged, but when i unplugged it got the same error(empty string). Most of my clients are not having net connection.

is there any alternate way to get mac address in win 7?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900