質問

アプリケーションを実行しているpcのbluetoothデバイスのmacアドレスを取得したい。

次のことを試しました:

private void GetMacAddress()
{
     string macAddresses = "";
     foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
     {
          if (nic.OperationalStatus == OperationalStatus.Up)
          {
               macAddresses += nic.GetPhysicalAddress().ToString();
               Console.WriteLine(macAddresses);
          }
     }
}

しかし、出力はcommandpromptの「ipconfig / all」と一致しません。 blueotths MACアドレスは出力されません。 解決策はありますか?

「ipconfig / all」から取得した出力を解析する準備ができていますが、出力を文字列として取得するにはどうすればよいですか

役に立ちましたか?

解決

WMIを使用して結果を取得できます。これにより、ネットワークデバイスをたどるWMIソリューションへのリンクがあります。

ウェブサイトがダウンした場合に備えてここにコードを投稿していますが、すべてのクレジットは元の作者であるPsychoCoderに帰属します。 WMIを使用してC#でMACアドレスを取得する

そしてコード:

//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 [&quot; Description&quot;]。ToString();

を使用できます。

WMIに関するMSDN、特に Win32_NetworkAdapterConfigurationクラス

これがお役に立てば幸いです。

他のヒント

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;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top