Advertisement
teplofizik

detect_usb_serial.cs

May 11th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Management;
  7.  
  8. namespace SuperPuperNamespace
  9. {
  10. static partial class Program
  11. {
  12. static List<USBDeviceInfo> GetUSBDevices()
  13. {
  14. List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
  15.  
  16. ManagementObjectCollection collection;
  17. using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity "))
  18. collection = searcher.Get();
  19.  
  20. foreach (var device in collection)
  21. {
  22. devices.Add(new USBDeviceInfo(
  23. (string)device.GetPropertyValue("DeviceID"),
  24. (string)device.GetPropertyValue("PNPDeviceID"),
  25. (string)device.GetPropertyValue("Description"),
  26. (string)device.GetPropertyValue("Name")
  27. ));
  28. }
  29.  
  30. collection.Dispose();
  31. return devices;
  32. }
  33.  
  34. // Выдаёт первый попавшийся usb-com с нужным вид-пидом
  35. static string GetSerialByUSB()
  36. {
  37. var usb = GetUSBDevices();
  38.  
  39. foreach(var U in usb)
  40. {
  41. // Вид-пид проверяем
  42. if(U.CheckVidPid(0x1234, 0x5678))
  43. {
  44. string Name = U.Name;
  45.  
  46. int Start = Name.IndexOf('(');
  47. int End = Name.IndexOf(')');
  48.  
  49. return Name.Substring(Start + 1, End - Start - 1);
  50. }
  51. }
  52.  
  53. return null;
  54. }
  55. }
  56.  
  57. class USBDeviceInfo
  58. {
  59. public USBDeviceInfo(string deviceID, string pnpDeviceID, string description, string Name)
  60. {
  61. this.DeviceID = deviceID;
  62. this.PnpDeviceID = pnpDeviceID;
  63. this.Description = description;
  64. this.Name = Name;
  65. }
  66. public string DeviceID { get; private set; }
  67. public string PnpDeviceID { get; private set; }
  68. public string Description { get; private set; }
  69. public string Name { get; private set; }
  70.  
  71. public bool CheckVidPid(int Vid, int Pid)
  72. {
  73. var VidS = String.Format("VID_{0:X4}", Vid);
  74. var PidS = String.Format("PID_{0:X4}", Pid);
  75.  
  76. return DeviceID.Contains(VidS) && DeviceID.Contains(PidS);
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement