如何从本地PC获取蓝牙MAC地址?
问题描述:
我想在我的应用程序运行的PC上获取蓝牙设备的MAC地址。如何从本地PC获取蓝牙MAC地址?
我曾尝试以下:
private void GetMacAddress()
{
string macAddresses = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
Console.WriteLine(macAddresses);
}
}
}
但产量不匹配 'IPCONFIG/ALL' 的commandprompt。它不打印我的blueotths mac地址。 任何解决方案?
我准备解析从'ipconfig/all'得到的输出,但是我怎样才能得到输出为字符串?
答
您也许可以使用WMI来获得结果。这里有一个指向WMI解决方案的链接,该链接通过网络设备。
我在这里发布的代码,以防万一网站关闭,但所有功劳都归于原作者PsychoCoder。 Use WMI to get MAC Address in C#
,代码:
//Namespace reference
using System.Management;
/// <summary>
/// Returns MAC Address from first Network Card in Computer
/// </summary>
/// <returns>MAC Address in string format</returns>
public string FindMACAddress()
{
//create out management class object using the
//Win32_NetworkAdapterConfiguration class to get the attributes
//af the network adapter
ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapterConfiguration");
//create our ManagementObjectCollection to get the attributes with
ManagementObjectCollection objCol = mgmt.GetInstances();
string address = String.Empty;
//My modification to the code
var description = String.Empty;
//loop through all the objects we find
foreach (ManagementObject obj in objCol)
{
if (address == String.Empty) // only return MAC Address from first card
{
//grab the value from the first network adapter we find
//you can change the string to an array and get all
//network adapters found as well
if ((bool)obj["IPEnabled"] == true)
{
address = obj["MacAddress"].ToString();
description = obj["Description"].ToString();
}
}
//dispose of our object
obj.Dispose();
}
//replace the ":" with an empty space, this could also
//be removed if you wish
address = address.Replace(":", "");
//return the mac address
return address;
}
请务必注明引用System.Management。 为了让您了解网络设备的名称,你可以使用obj["Description"].ToString();
您还可以看看MSDN关于WMI,专门给Win32_NetworkAdapterConfiguration Class
希望这有助于。
答
public static PhysicalAddress GetBTMacAddress() {
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {
// Only consider Bluetooth network interfaces
if (nic.NetworkInterfaceType != NetworkInterfaceType.FastEthernetFx &&
nic.NetworkInterfaceType != NetworkInterfaceType.Wireless80211){
return nic.GetPhysicalAddress();
}
}
return null;
}
酷!有效。谢谢:) – 2009-11-30 14:49:48
很高兴我能帮上忙。 – Riaan 2009-11-30 16:05:46