我試圖以編程方式獲取我的系統的MAC地址。我正在用C#編寫,在Windows 10操作系統上使用Visual Studios .NET框架。我已經包含了System.Net.NetworkInformation命名空間(對於像我這樣的其他.NET新手而言,必須將其手動添加到解決方案資源管理器的「參考」部分,然後使用「使用」關鍵字)。要獲得MAC地址,我使用下面的代碼:當我嘗試獲取我的MAC地址時,爲什麼會收到空字符串?
try
{
var macAddr =
(
from nic in NetworkInterface.GetAllNetworkInterfaces()
where nic.OperationalStatus == OperationalStatus.Up
select nic.GetPhysicalAddress().ToString()
).FirstOrDefault();
Console.WriteLine("MAC address is: {0}", macAddr);
}
catch (Exception e)
{
Console.WriteLine("Could not collect MAC Address;\nERROR: {0}", e);
}
,我期待的輸出可以是:
Attempting to collect MAC Address...
MAC address is: XXXXXXXXXXXX
其中XXX ....是12個字符的MAC地址,或:
Attempting to collect MAC Address...
Could not collect MAC Address;
ERROR: [error report inserted here]
什麼我得到,但是,是這樣的:
Attempting to collect MAC Address...
MAC address is:
其中macAddr變量似乎收集了一個空字符串。
所以......我的問題是,爲什麼我得到一個明顯爲空的字符串,而不是我期待的12個字符的MAC地址?
什麼是生成的異常? –
正在生成沒有例外。 try語句成功,但沒有打印MAC地址。 – MrSpudtastic