來源:http://www.cnblogs.com/hshuzhao/p/4028856.html?utm_source=tuicool&utm_medium=referral
、情境:
做專案的時候要開啟串列埠然後進行一些庫函式的呼叫來操作目標板。串列埠使用的是usb轉串列埠,板子插進拔出的,每次都使用不一樣的usb口,debug的時候懶得每次改com口,又不想在UI上加上一個選擇
com口的combox,於是就使用了下面這個方法。
2、環境:
win7 64、vs2010
3、目標:
獲取下圖的裝置到底使用的是com幾。
4、source codery>

1 /// <summary>
2 /// Get the target com num.
3 /// </summary>
4 /// <returns></returns>
5 public static int GetComNum()
6 {
7 int comNum = -1;
8 string[] strArr = GetHarewareInfo(HardwareEnum.Win32_PnPEntity, "Name");
9 foreach (string s in strArr)
10 {
11 Debug.WriteLine(s);
12
13 if (s.Length >= 23 && s.Contains("CH340"))
14 {
15 int start = s.IndexOf("(") + 3;
16 int end = s.IndexOf(")");
17 comNum = Convert.ToInt32(s.Substring(start + 1, end - start - 1));
18 }
19 }
20
21 return comNum;
22
23 }
24
25 /// <summary>
26 /// Get the system devices information with windows api.
27 /// </summary>
28 /// <param name="hardType">Device type.</param>
29 /// <param name="propKey">the property of the device.</param>
30 /// <returns></returns>
31 private static string[] GetHarewareInfo(HardwareEnum hardType, string propKey)
32 {
33
34 List<string> strs = new List<string>();
35 try
36 {
37 using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType))
38 {
39 var hardInfos = searcher.Get();
40 foreach (var hardInfo in hardInfos)
41 {
42 if (hardInfo.Properties[propKey].Value != null)
43 {
44 String str = hardInfo.Properties[propKey].Value.ToString();
45 strs.Add(str);
46 }
47
48 }
49 }
50 return strs.ToArray();
51 }
52 catch
53 {
54 return null;
55 }
56 finally
57 {
58 strs = null;
59 }
60 }//end of func GetHarewareInfo().
61
62 /// <summary>
63 /// 列舉win32 api
64 /// </summary>
65 public enum HardwareEnum
66 {
67 // 硬體
68 Win32_Processor, // CPU 處理器
69 Win32_PhysicalMemory, // 實體記憶體條
70 Win32_Keyboard, // 鍵盤
71 Win32_PointingDevice, // 點輸入裝置,包括滑鼠。
72 Win32_FloppyDrive, // 軟盤驅動器
73 Win32_DiskDrive, // 硬碟驅動器
74 Win32_CDROMDrive, // 光碟驅動器
75 Win32_BaseBoard, // 主機板
76 Win32_BIOS, // BIOS 晶片
77 Win32_ParallelPort, // 並口
78 Win32_SerialPort, // 串列埠
79 Win32_SerialPortConfiguration, // 串列埠配置
80 Win32_SoundDevice, // 多媒體設定,一般指音效卡。
81 Win32_SystemSlot, // 主機板插槽 (ISA & PCI & AGP)
82 Win32_USBController, // USB 控制器
83 Win32_NetworkAdapter, // 網路介面卡
84 Win32_NetworkAdapterConfiguration, // 網路介面卡設定
85 Win32_Printer, // 印表機
86 Win32_PrinterConfiguration, // 印表機設定
87 Win32_PrintJob, // 印表機任務
88 Win32_TCPIPPrinterPort, // 印表機埠
89 Win32_POTSModem, // MODEM
90 Win32_POTSModemToSerialPort, // MODEM 埠
91 Win32_DesktopMonitor, // 顯示器
92 Win32_DisplayConfiguration, // 顯示卡
93 Win32_DisplayControllerConfiguration, // 顯示卡設定
94 Win32_VideoController, // 顯示卡細節。
95 Win32_VideoSettings, // 顯示卡支援的顯示模式。
96
97 // 作業系統
98 Win32_TimeZone, // 時區
99 Win32_SystemDriver, // 驅動程式
100 Win32_DiskPartition, // 磁碟分割槽
101 Win32_LogicalDisk, // 邏輯磁碟
102 Win32_LogicalDiskToPartition, // 邏輯磁碟所在分割槽及始末位置。
103 Win32_LogicalMemoryConfiguration, // 邏輯記憶體配置
104 Win32_PageFile, // 系統頁檔案資訊
105 Win32_PageFileSetting, // 頁檔案設定
106 Win32_BootConfiguration, // 系統啟動配置
107 Win32_ComputerSystem, // 計算機資訊簡要
108 Win32_OperatingSystem, // 作業系統資訊
109 Win32_StartupCommand, // 系統自動啟動程式
110 Win32_Service, // 系統安裝的服務
111 Win32_Group, // 系統管理組
112 Win32_GroupUser, // 系統組帳號
113 Win32_UserAccount, // 使用者帳號
114 Win32_Process, // 系統程序
115 Win32_Thread, // 系統執行緒
116 Win32_Share, // 共享
117 Win32_NetworkClient, // 已安裝的網路客戶端
118 Win32_NetworkProtocol, // 已安裝的網路協議
119 Win32_PnPEntity,//all device
120 }

6、結果:
正確獲得對應的com口號,達到了隨便插哪個口程式都可以跑的目的。