DeviceInterfaceUtils.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /* Copyright (C) 2014-2017 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Runtime.InteropServices;
  11. using System.Text;
  12. using Microsoft.Win32.SafeHandles;
  13. namespace DiskAccessLibrary
  14. {
  15. [Flags]
  16. public enum DiGetClassFlags : uint
  17. {
  18. DIGCF_DEFAULT = 0x00000001, // only valid with DIGCF_DEVICEINTERFACE
  19. DIGCF_PRESENT = 0x00000002,
  20. DIGCF_ALLCLASSES = 0x00000004,
  21. DIGCF_PROFILE = 0x00000008,
  22. DIGCF_DEVICEINTERFACE = 0x00000010,
  23. }
  24. [StructLayout(LayoutKind.Sequential)]
  25. public struct SP_DEVINFO_DATA
  26. {
  27. public uint cbSize;
  28. public Guid ClassGuid;
  29. public uint DevInst;
  30. public IntPtr Reserved;
  31. }
  32. [StructLayout(LayoutKind.Sequential)]
  33. public struct SP_DEVICE_INTERFACE_DATA
  34. {
  35. public uint cbSize;
  36. public Guid InterfaceClassGuid;
  37. public uint Flags;
  38. public IntPtr Reserved;
  39. }
  40. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  41. public struct SP_DEVICE_INTERFACE_DETAIL_DATA
  42. {
  43. public uint cbSize;
  44. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
  45. public string DevicePath;
  46. }
  47. public class DeviceInfo
  48. {
  49. public string DevicePath;
  50. public string DeviceDescription;
  51. public string FriendlyName;
  52. /// <summary>
  53. /// Device manager shows the friendly name if it exists and the device description otherwise.
  54. /// </summary>
  55. public string DeviceName
  56. {
  57. get
  58. {
  59. if (!String.IsNullOrEmpty(FriendlyName))
  60. {
  61. return FriendlyName;
  62. }
  63. else
  64. {
  65. return DeviceDescription;
  66. }
  67. }
  68. }
  69. }
  70. public class DeviceInterfaceUtils // SetupDi functions
  71. {
  72. public static readonly Guid DiskClassGuid = new Guid("53F56307-B6BF-11D0-94F2-00A0C91EFB8B");
  73. public static readonly Guid CDRomClassGuid = new Guid("53F56308-B6BF-11D0-94F2-00A0C91EFB8B");
  74. public static readonly Guid TapeClassGuid = new Guid("53F5630B-B6BF-11D0-94F2-00A0C91EFB8B");
  75. public static readonly Guid MediumChangerClassGuid = new Guid("53F56310-B6BF-11D0-94F2-00A0C91EFB8B");
  76. public static readonly Guid StoragePortClassGuid = new Guid("2ACCFE60-C130-11D2-B082-00A0C91EFB8B");
  77. private const Int64 INVALID_HANDLE_VALUE = -1;
  78. private const uint SPDRP_DEVICEDESC = 0x00000000;
  79. private const uint SPDRP_FRIENDLYNAME = 0x0000000C;
  80. [DllImport("setupapi.dll", CharSet = CharSet.Auto)]
  81. private static extern IntPtr SetupDiGetClassDevs( // 1st form using a ClassGUID only, with null Enumerator
  82. ref Guid classGuid,
  83. IntPtr enumerator,
  84. IntPtr hwndParent,
  85. uint flags
  86. );
  87. [DllImport("setupapi.dll", SetLastError = true)]
  88. private static extern bool SetupDiDestroyDeviceInfoList
  89. (
  90. IntPtr deviceInfoSet
  91. );
  92. [DllImport("setupapi.dll", SetLastError = true)]
  93. private static extern bool SetupDiEnumDeviceInfo(
  94. IntPtr deviceInfoSet,
  95. uint memberIndex,
  96. ref SP_DEVINFO_DATA deviceInfoData // Out
  97. );
  98. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  99. private static extern Boolean SetupDiEnumDeviceInterfaces(
  100. IntPtr deviceInfoSet,
  101. ref SP_DEVINFO_DATA deviceInfoData,
  102. ref Guid interfaceClassGuid,
  103. UInt32 memberIndex,
  104. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData
  105. );
  106. // Alternate signature if you do not care about SP_DEVINFO_DATA and wish to pass NULL (IntPtr.Zero)
  107. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  108. private static extern Boolean SetupDiEnumDeviceInterfaces(
  109. IntPtr deviceInfoSet,
  110. IntPtr deviceInfoData,
  111. ref Guid interfaceClassGuid,
  112. UInt32 memberIndex,
  113. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData
  114. );
  115. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  116. private static extern Boolean SetupDiGetDeviceInterfaceDetail(
  117. IntPtr deviceInfoSet,
  118. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
  119. ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
  120. UInt32 deviceInterfaceDetailDataSize,
  121. out UInt32 requiredSize,
  122. ref SP_DEVINFO_DATA deviceInfoData
  123. );
  124. // Alternate signature if you do not care about SP_DEVINFO_DATA and wish to pass NULL (IntPtr.Zero)
  125. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  126. private static extern Boolean SetupDiGetDeviceInterfaceDetail(
  127. IntPtr deviceInfoSet,
  128. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
  129. ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
  130. UInt32 deviceInterfaceDetailDataSize,
  131. out UInt32 requiredSize,
  132. IntPtr deviceInfoData
  133. );
  134. // Alternate signature - first call (we wish to pass IntPtr instead of reference to SP_DEVICE_INTERFACE_DETAIL_DATA)
  135. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  136. private static extern Boolean SetupDiGetDeviceInterfaceDetail(
  137. IntPtr deviceInfoSet,
  138. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
  139. IntPtr deviceInterfaceDetailData,
  140. UInt32 deviceInterfaceDetailDataSize,
  141. out UInt32 requiredSize,
  142. IntPtr deviceInfoData
  143. );
  144. [DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  145. private static extern bool SetupDiGetDeviceRegistryProperty(
  146. IntPtr deviceInfoSet,
  147. ref SP_DEVINFO_DATA deviceInfoData,
  148. UInt32 property,
  149. out UInt32 propertyRegDataType,
  150. byte[] propertyBuffer, // The caller will allocate this byte array for the callee to fill
  151. UInt32 propertyBufferSize,
  152. out UInt32 requiredSize
  153. );
  154. /// <summary>
  155. /// returns a handle to a device information set that contains requested device information elements.
  156. ///
  157. /// The caller must delete the returned device information set when it is no longer needed
  158. /// by calling DestroyDeviceInfoList().
  159. /// </summary>
  160. // http://msdn.microsoft.com/en-us/library/windows/hardware/ff551069%28v=vs.85%29.aspx
  161. public static IntPtr GetClassDevices(Guid classGuid)
  162. {
  163. uint flags = (uint)(DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE); // Only Devices present & Interface class
  164. IntPtr deviceInfoSet = SetupDiGetClassDevs(ref classGuid, IntPtr.Zero, IntPtr.Zero, flags);
  165. if (deviceInfoSet.ToInt64() == INVALID_HANDLE_VALUE)
  166. {
  167. int errorCode = Marshal.GetLastWin32Error();
  168. string message = String.Format("Unable to retrieve class devices, Win32 Error: {0}", errorCode);
  169. throw new IOException(message);
  170. }
  171. else
  172. {
  173. return deviceInfoSet;
  174. }
  175. }
  176. public static void DestroyDeviceInfoList(IntPtr deviceInfoSet)
  177. {
  178. bool success = SetupDiDestroyDeviceInfoList(deviceInfoSet);
  179. if (!success)
  180. {
  181. int errorCode = Marshal.GetLastWin32Error();
  182. string message = String.Format("Unable to destroy device info list, Win32 Error: {0}", errorCode);
  183. throw new IOException(message);
  184. }
  185. }
  186. // http://msdn.microsoft.com/en-us/library/windows/hardware/ff551120%28v=vs.85%29.aspx
  187. public static SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceDetail(IntPtr deviceInfoSet, SP_DEVICE_INTERFACE_DATA deviceInterfaceData)
  188. {
  189. // For ERROR_INVALID_USER_BUFFER error see:
  190. // http://msdn.microsoft.com/en-us/library/windows/hardware/ff552343%28v=vs.85%29.aspx
  191. // http://stackoverflow.com/questions/10728644/properly-declare-sp-device-interface-detail-data-for-pinvoke
  192. uint requiredSize;
  193. SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
  194. bool success = SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, IntPtr.Zero, 0, out requiredSize, IntPtr.Zero);
  195. if (!success)
  196. {
  197. int errorCode = Marshal.GetLastWin32Error();
  198. if (errorCode == (int)Win32Error.ERROR_INSUFFICIENT_BUFFER)
  199. {
  200. uint size = requiredSize;
  201. // cbSize should parallel to sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA) in C
  202. // cbSize is calculated as sizeof(DWORD) + padding + sizeof(TCHAR) + padding
  203. int cbSize;
  204. if (IntPtr.Size == 4)
  205. {
  206. cbSize = sizeof(uint) + Marshal.SystemDefaultCharSize;
  207. }
  208. else
  209. {
  210. // take x64 padding into account
  211. cbSize = sizeof(uint) + 4;
  212. }
  213. IntPtr lpOutBuffer = Marshal.AllocHGlobal((int)size);
  214. Marshal.WriteInt32(lpOutBuffer, cbSize);
  215. success = SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, lpOutBuffer, size, out requiredSize, IntPtr.Zero);
  216. deviceInterfaceDetailData = (SP_DEVICE_INTERFACE_DETAIL_DATA)Marshal.PtrToStructure(lpOutBuffer, typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
  217. Marshal.FreeHGlobal(lpOutBuffer);
  218. if (!success)
  219. {
  220. errorCode = Marshal.GetLastWin32Error();
  221. string message = String.Format("Unable to retrieve device interface detail data, Win32 Error: {0}", errorCode);
  222. throw new IOException(message);
  223. }
  224. }
  225. else
  226. {
  227. errorCode = Marshal.GetLastWin32Error();
  228. string message = String.Format("Unable to retrieve device interface detail data, Win32 Error: {0}", errorCode);
  229. throw new IOException(message);
  230. }
  231. }
  232. return deviceInterfaceDetailData;
  233. }
  234. // Great C++ Example of enumerating and locating specific attach storage devices:
  235. // http://code.msdn.microsoft.com/windowshardware/CppStorageEnum-90ad5fa9
  236. public static List<string> GetDevicePathList(Guid deviceClassGuid)
  237. {
  238. IntPtr deviceInfoSet = GetClassDevices(deviceClassGuid);
  239. SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
  240. deviceInterfaceData.cbSize = (uint)Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DATA));
  241. uint index = 0;
  242. List<string> result = new List<string>();
  243. while (true)
  244. {
  245. bool success = SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref deviceClassGuid, index, ref deviceInterfaceData);
  246. if (!success)
  247. {
  248. int errorCode = Marshal.GetLastWin32Error();
  249. if (errorCode == (int)Win32Error.ERROR_NO_MORE_ITEMS)
  250. {
  251. break;
  252. }
  253. else
  254. {
  255. string message = String.Format("Unable to enumerate device interfaces, Win32 Error: {0}", errorCode);
  256. throw new IOException(message);
  257. }
  258. }
  259. SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = GetDeviceInterfaceDetail(deviceInfoSet, deviceInterfaceData);
  260. result.Add(deviceInterfaceDetailData.DevicePath);
  261. index++;
  262. }
  263. DestroyDeviceInfoList(deviceInfoSet);
  264. return result;
  265. }
  266. private static string GetDeviceStringProperty(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, uint property)
  267. {
  268. uint propertyRegDataType;
  269. byte[] propertyBuffer = new byte[128];
  270. uint requiredSize;
  271. bool success = SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, property, out propertyRegDataType, propertyBuffer, (uint)propertyBuffer.Length, out requiredSize);
  272. if (!success)
  273. {
  274. int errorCode = Marshal.GetLastWin32Error();
  275. if (errorCode == (int)Win32Error.ERROR_INSUFFICIENT_BUFFER)
  276. {
  277. propertyBuffer = new byte[requiredSize];
  278. success = SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, property, out propertyRegDataType, propertyBuffer, (uint)propertyBuffer.Length, out requiredSize);
  279. }
  280. else if (errorCode == (int)Win32Error.ERROR_INVALID_DATA)
  281. {
  282. return null;
  283. }
  284. if (!success)
  285. {
  286. string message = String.Format("Unable to retrieve property, Win32 Error: {0}", errorCode);
  287. throw new IOException(message);
  288. }
  289. }
  290. string value = UnicodeEncoding.Unicode.GetString(propertyBuffer, 0, (int)requiredSize);
  291. value = value.TrimEnd(new char[] { '\0' });
  292. return value;
  293. }
  294. // https://msdn.microsoft.com/windows/hardware/drivers/install/device-information-sets
  295. public static List<DeviceInfo> GetDeviceList(Guid deviceClassGuid)
  296. {
  297. IntPtr deviceInfoSet = GetClassDevices(deviceClassGuid);
  298. SP_DEVINFO_DATA deviceInfoData = new SP_DEVINFO_DATA();
  299. deviceInfoData.cbSize = (uint)Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
  300. SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
  301. deviceInterfaceData.cbSize = (uint)Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DATA));
  302. uint index = 0;
  303. List<DeviceInfo> result = new List<DeviceInfo>();
  304. while (true)
  305. {
  306. bool success = SetupDiEnumDeviceInfo(deviceInfoSet, index, ref deviceInfoData);
  307. if (!success)
  308. {
  309. int errorCode = Marshal.GetLastWin32Error();
  310. if (errorCode == (int)Win32Error.ERROR_NO_MORE_ITEMS)
  311. {
  312. break;
  313. }
  314. else
  315. {
  316. string message = String.Format("Unable to enumerate devices, Win32 Error: {0}", errorCode);
  317. throw new IOException(message);
  318. }
  319. }
  320. success = SetupDiEnumDeviceInterfaces(deviceInfoSet, ref deviceInfoData, ref deviceClassGuid, 0, ref deviceInterfaceData);
  321. if (!success)
  322. {
  323. int errorCode = Marshal.GetLastWin32Error();
  324. string message = String.Format("Unable to enumerate device interfaces, Win32 Error: {0}", errorCode);
  325. throw new IOException(message);
  326. }
  327. SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = GetDeviceInterfaceDetail(deviceInfoSet, deviceInterfaceData);
  328. DeviceInfo deviceInfo = new DeviceInfo();
  329. deviceInfo.DevicePath = deviceInterfaceDetailData.DevicePath;
  330. deviceInfo.DeviceDescription = GetDeviceStringProperty(deviceInfoSet, deviceInfoData, SPDRP_DEVICEDESC);
  331. deviceInfo.FriendlyName = GetDeviceStringProperty(deviceInfoSet, deviceInfoData, SPDRP_FRIENDLYNAME);
  332. result.Add(deviceInfo);
  333. index++;
  334. }
  335. DestroyDeviceInfoList(deviceInfoSet);
  336. return result;
  337. }
  338. }
  339. }