Wednesday, February 21, 2007

C# .Net 2.0 Get MAC Address with WMI

Problem:

Need to get the MAC address from workstation where
software is installed.


Solution:

.Net 2.0
C#

Add Reference: System.Management


private string GetMacAddress()
{
//ManagementObjectSearcher namespace is System.Management
//add .Net reference

ManagementObjectSearcher query = null;
ManagementObjectCollection queryCollection = null;

try
{
query = new
ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");

queryCollection = query.Get();


foreach (ManagementObject mo in queryCollection)
{
if ((bool)mo["IPEnabled"] == true)
{
//System.Diagnostics.Debug.WriteLine(mo.GetText(TextFormat.Mof));
string mac_address = mo["MacAddress"].ToString();

mo.Dispose();
queryCollection.Dispose();
query.Dispose();

return (mac_address);
}
}

return (string.Empty);

}
catch (System.Exception er)
{
System.Diagnostics.Debug.WriteLine(er.Message.ToString());
return (string.Empty);
}
}

No comments: