private static object GetDeviceRegistryProperty(IntPtr h, ref Hardware.SP_DEVINFO_DATA devInfo, RegistryProperty property) { RegistryDataType dataType; uint bufferLength; SetupDiGetDeviceRegistryProperty(h, ref devInfo, property, out dataType, IntPtr.Zero, 0, out bufferLength); object result = null; IntPtr buffer = Marshal.AllocHGlobal((int)bufferLength); if (SetupDiGetDeviceRegistryProperty(h, ref devInfo, property, out dataType, buffer, bufferLength, out bufferLength)) { switch (dataType) { case RegistryDataType.REG_SZ: result = Marshal.PtrToStringAuto(buffer); break; case RegistryDataType.REG_MULTI_SZ: var bytes = PtrToByteArray(buffer, bufferLength); var text = Encoding.Unicode.GetString(bytes); result = text.TrimEnd('\0').Split('\0'); break; case RegistryDataType.REG_BINARY: result = PtrToByteArray(buffer, bufferLength); break; case RegistryDataType.REG_DWORD: result = Marshal.ReadInt32(buffer); break; default: throw new Exception(string.Format("Unsupported data type: {0}", dataType)); } } Marshal.FreeHGlobal(buffer); return result; }
protected static extern bool SetupDiGetDeviceRegistryProperty(IntPtr DeviceInfoSet, ref DeviceInfoData DeviceInfoData, RegistryProperty Property, out RegistryValueKind PropertyRegDataType, IntPtr PropertyBuffer, uint PropertyBufferSize, out uint RequiredSize);
static string ReadPropertyString(IntPtr infoSetPtr, ref DeviceInfoData deviceInfo, RegistryProperty property) { RegistryValueKind valueKind; uint requiredSize; SetupDiGetDeviceRegistryProperty(infoSetPtr, ref deviceInfo, property, out valueKind, IntPtr.Zero, 0, out requiredSize); var lastError = Marshal.GetLastWin32Error(); if (ERROR_INSUFFICIENT_BUFFER == lastError) { Contract.Assert(new[] { RegistryValueKind.ExpandString, RegistryValueKind.MultiString, RegistryValueKind.String } .Contains(valueKind)); IntPtr buffer = Marshal.AllocHGlobal((int)requiredSize); try { if (SetupDiGetDeviceRegistryProperty(infoSetPtr, ref deviceInfo, property, out valueKind, buffer, requiredSize, out requiredSize)) { return(Marshal.PtrToStringAuto(buffer)); } lastError = Marshal.GetLastWin32Error(); } finally { Marshal.FreeHGlobal(buffer); } } if (ERROR_INVALID_DATA == lastError) { return(string.Empty); } throw new Win32Exception(lastError) { Source = "WinUSB.SetupDiGetDeviceRegistryProperty" }; }