LoginSignup
1
1

More than 5 years have passed since last update.

[C#] シリアルポート列挙

Last updated at Posted at 2015-08-19

基本的には、以下のサイト
http://truthfullscore.hatenablog.com/entry/2014/01/10/180608
とほぼ同じ。ただし、Win32_PnPEntityを利用するとうまくCOMポートが取れない場合があったので、Win32_SerilPortを利用した。

以下のコードは、コンソールに情報を列挙するだけだが、得られた情報を正規表現等で検索すればCOM番号を取得できる。

using System;
using System.Management;    // add to reference settings

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("show COM port");

            ManagementClass device = new ManagementClass("Win32_SerialPort");
            //ManagementClass device = new ManagementClass("Win32_PnPEntity");

            foreach (ManagementObject port in device.GetInstances())
            {
                Console.WriteLine("[device ] {0}", (string)port.GetPropertyValue("DeviceID"));
                Console.WriteLine("[caption] {0}", (string)port.GetPropertyValue("Caption"));
            }

            Console.WriteLine("\n\n--- hit enter key to end program");
            Console.ReadLine();
        }
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1