C#.net - Get MAC Address
Sometime in our application we need to fetch MAC Address of network adapter card.In this article i will show you how to get a MAC Address.
Step 1
Create a Console Application and give the solution name as ConMACAddress.
Step 2
Add System.Management assembly reference to the project from solution explorer,it is look like this
Click on image for better view
Step 3
Write a static method for get MAC Address,it is look like this
Step 4
Call above function in main method,it is look like this
Run the Project.
Full Code
Download
Download Source Code
Step 1
Create a Console Application and give the solution name as ConMACAddress.
Step 2
Add System.Management assembly reference to the project from solution explorer,it is look like this
Click on image for better view
Step 3
Write a static method for get MAC Address,it is look like this
- public static String GetMACAddress()
- {
- #region Get MAC Address
- try
- {
- ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
- ManagementObjectCollection moc = mc.GetInstances();
- string MACAddress = String.Empty;
- 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;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- #endregion
- }
Step 4
Call above function in main method,it is look like this
- static void Main(string[] args)
- {
- try
- {
- System.Console.WriteLine("MAC Address\t:\t" + GetMACAddress());
- }
- catch (Exception ex)
- {
- System.Console.WriteLine(ex.Message);
- }
- }
Run the Project.
Full Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Management;
- namespace ConMACAddress
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- System.Console.WriteLine("MAC Address\t:\t" + GetMACAddress());
- }
- catch (Exception ex)
- {
- System.Console.WriteLine(ex.Message);
- }
- }
- public static String GetMACAddress()
- {
- #region Get MAC Address
- try
- {
- ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
- ManagementObjectCollection moc = mc.GetInstances();
- string MACAddress = String.Empty;
- 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;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message);
- }
- #endregion
- }
- }
- }
Download
Download Source Code