2013-04-03 14 views
9

C'è un modo per ottenere l'indirizzo mac del computer quando non c'è connessione a Internet in C#? Sono in grado di ottenere quando ho una connessione ma non riesco a ottenere quando sono offline. Ma ho fortemente bisogno dell'indirizzo mac per il mio lavoro.C# Ottieni l'indirizzo MAC del computer "OFFLINE"

Il mio codice online;

var macAddr = 
     (from nic in NetworkInterface.GetAllNetworkInterfaces() 
     where nic.OperationalStatus == OperationalStatus.Up 
     select nic.GetPhysicalAddress().ToString()).FirstOrDefault(); 
+0

si può solo togliere la 'dove nic.OperationalStatus = = Riga OperationalStatus.Up'? – Pondidum

+0

Se online, indirizzo mac; 4CEB428D5072 Se non in linea, indirizzo mac 4CEB428D5073. Perché? –

risposta

24

Da WMI:

public static string GetMACAddress1() 
{ 
    ManagementObjectSearcher objMOS = new ManagementObjectSearcher("Select * FROM Win32_NetworkAdapterConfiguration"); 
    ManagementObjectCollection objMOC = objMOS.Get(); 
    string macAddress = String.Empty; 
    foreach (ManagementObject objMO in objMOC) 
    { 
     object tempMacAddrObj = objMO["MacAddress"]; 

     if (tempMacAddrObj == null) //Skip objects without a MACAddress 
     { 
      continue; 
     } 
     if (macAddress == String.Empty) // only return MAC Address from first card that has a MAC Address 
     { 
      macAddress = tempMacAddrObj.ToString();    
     } 
     objMO.Dispose(); 
    } 
    macAddress = macAddress.Replace(":", ""); 
    return macAddress; 
} 

Da System.Net namespace:

public static string GetMACAddress2() 
{ 
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); 
    String sMacAddress = string.Empty; 
    foreach (NetworkInterface adapter in nics) 
    { 
     if (sMacAddress == String.Empty)// only return MAC Address from first card 
     { 
      //IPInterfaceProperties properties = adapter.GetIPProperties(); Line is not required 
      sMacAddress = adapter.GetPhysicalAddress().ToString(); 
     } 
    } return sMacAddress; 
} 

leggermente modificato da How to get the MAC address of system - C-Sharp Corner

+0

La riga 'Proprietà IPInterfaceProperties = adapter.GetIPProperties();' necessaria? – Joel

+0

@Joel No questa riga non è richiesta in base al test Ho appena eseguito la mia finestra di sviluppo. Risposta aggiornata per riflettere i miei test. – jordanhill123

Problemi correlati