C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 300,497 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,850 people online right now. Registration is fast and FREE... Join Now!





Use WMI to get MAC Address in C#

This is a snippet that can be used to retrieve the MAC address of a network adapter

Submitted By: PsychoCoder
Actions:
Rating:
Views: 11,241

Language: C#

Last Modified: February 10, 2008
Instructions: Add a reference to the System.Management Namespace, call the method and the value will be returned in string format

Snippet


  1. //Namespace reference
  2. using System.Management;
  3.  
  4. /// <summary>
  5. /// Returns MAC Address from first Network Card in Computer
  6. /// </summary>
  7. /// <returns>MAC Address in string format</returns>
  8. public string FindMACAddress()
  9. {
  10.     //create out management class object using the
  11.     //Win32_NetworkAdapterConfiguration class to get the attributes
  12.     //af the network adapter
  13.     ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapterConfiguration");
  14.     //create our ManagementObjectCollection to get the attributes with
  15.     ManagementObjectCollection objCol = mgmt.GetInstances();
  16.     string address = String.Empty;
  17.     //loop through all the objects we find
  18.     foreach (ManagementObject obj in objCol)
  19.     {
  20.         if (address == String.Empty)  // only return MAC Address from first card
  21.         {
  22.             //grab the value from the first network adapter we find
  23.             //you can change the string to an array and get all
  24.             //network adapters found as well
  25.             if ((bool)obj["IPEnabled"] == true) address = obj["MacAddress"].ToString();
  26.         }
  27.         //dispose of our object
  28.         obj.Dispose();
  29.     }
  30.     //replace the ":" with an empty space, this could also
  31.     //be removed if you wish
  32.     address = address.Replace(":", "");
  33.     //return the mac address
  34.     return address;
  35. }

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month