public static string GetInstanceIDByKeyName(string driverKeyName) { var result = string.Empty; var h = SetupApi.SetupDiGetClassDevs(default(int), UsbConstants.REGSTR_KEY_USB, IntPtr.Zero, UsbConstants.DIGCF_PRESENT | UsbConstants.DIGCF_ALLCLASSES); if (h.ToInt32() != UsbConstants.INVALID_HANDLE_VALUE) { var ptrBuf = Marshal.AllocHGlobal(UsbConstants.BUFFER_SIZE); var keyName = string.Empty; var i = default(int); var success = default(bool); do { var da = new SpDevinfoData(); da.cbSize = Marshal.SizeOf(da); success = SetupApi.SetupDiEnumDeviceInfo(h, i, ref da); if (success) { var regType = UsbConstants.REG_SZ; var requiredSize = default(int); keyName = string.Empty; if (SetupApi.SetupDiGetDeviceRegistryProperty(h, ref da, UsbConstants.SPDRP_DRIVER, ref regType, ptrBuf, UsbConstants.BUFFER_SIZE, ref requiredSize)) { keyName = Marshal.PtrToStringAuto(ptrBuf); } if (keyName == driverKeyName) { var nBytes = UsbConstants.BUFFER_SIZE; var sb = new StringBuilder(nBytes); SetupApi.SetupDiGetDeviceInstanceId(h, ref da, sb, nBytes, out requiredSize); result = sb.ToString(); break; } } i++; } while (success); Marshal.FreeHGlobal(ptrBuf); SetupApi.SetupDiDestroyDeviceInfoList(h); } return(result); }
public static string GetDeviceInstanceId(string enum_device) // Returns the device instance ID of the specified device // 'enum_device' should have the following format: // <enumerator>\<device_id> { const int BUFFER_SIZE = 4096; string enumerator = enum_device.Split(new char[] { '\\' })[0]; StringBuilder deviceInstanceId = new StringBuilder(BUFFER_SIZE); SetupApi.SP_DEVINFO_DATA devInfoData; int reqSize; using (SetupApi.DeviceInfoSet devInfoSet = new SetupApi.DeviceInfoSet( IntPtr.Zero, enumerator, IntPtr.Zero, SetupApi.DiGetClassFlags.DIGCF_ALLCLASSES | SetupApi.DiGetClassFlags.DIGCF_PRESENT)) { devInfoData = Device.FindInSystem( enum_device, devInfoSet, false ); if (devInfoData == null) { return(""); } if (!SetupApi.SetupDiGetDeviceInstanceId( devInfoSet.Get(), devInfoData, deviceInstanceId, BUFFER_SIZE, out reqSize)) { Win32Error.Set("SetupDiGetDeviceInstanceId"); throw new Exception(Win32Error.GetFullErrMsg()); } } return(deviceInstanceId.ToString()); }