How to Get Mac Address

D

david

Hi All,

I have to get the MAC address in my program. But I didn't have the correct
property name of management object. And I don't know how to get it. Can some
one help me?

Below is my code.

Thanks,



ManagementClass adapters = new ManagementClass("Win32_NetworkAdapter");

string mac = "";
adapters.Get();
int ix =adapters.Properties.Count;
ix = adapters.Properties.Count;
foreach (ManagementObject adapter in adapters.GetInstances())
{
mac = adapter["Name"].ToString() + " " ;
mac += adapter["MACAddress"].ToString(); <--- crashed here,
propertyname is wrong.
 
N

Nick Wienholt

The MACAddress for some adapters will be null, which is probably the cause
of your problem. On my system, this code:

ManagementClass adapters = new ManagementClass("Win32_NetworkAdapter");

string mac = "";
adapters.Get();
foreach (ManagementObject adapter in adapters.GetInstances()) {
mac = adapter["Name"].ToString() + " " ;
Console.WriteLine(mac);
if (adapter["MACAddress"] != null){
mac += adapter["MACAddress"].ToString();
Console.WriteLine(mac);
}
Console.WriteLine();
}
Console.ReadLine();


produces this output:

VMware Virtual Ethernet Adapter for VMnet1
VMware Virtual Ethernet Adapter for VMnet1 00:50:56:C0:00:01

WAN Miniport (L2TP)

WAN Miniport (PPTP)
WAN Miniport (PPTP) 50:50:54:50:30:30

WAN Miniport (PPPOE)
WAN Miniport (PPPOE) 33:50:6F:45:30:30

Direct Parallel

WAN Miniport (IP)

VMware Virtual Ethernet Adapter for VMnet8
VMware Virtual Ethernet Adapter for VMnet8 00:50:56:C0:00:08

Microsoft Broadband Networking Wireless Notebook Adapter

Microsoft TV/Video Connection

Infrared Port




Nick Wienholt, MVP
Maximizing .NET Performance
http://www.apress.com/book/bookDisplay.html?bID=217
Sydney Deep .NET User Group www.sdnug.org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top