DeviceInterfaceUtils.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /* Copyright (C) 2014 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 DeviceInterfaceUtils // SetupDi functions
  48. {
  49. public static readonly Guid DiskClassGuid = new Guid("53F56307-B6BF-11D0-94F2-00A0C91EFB8B");
  50. const Int64 INVALID_HANDLE_VALUE = -1;
  51. [DllImport("setupapi.dll", CharSet = CharSet.Auto)]
  52. private static extern IntPtr SetupDiGetClassDevs( // 1st form using a ClassGUID only, with null Enumerator
  53. ref Guid ClassGuid,
  54. IntPtr Enumerator,
  55. IntPtr hwndParent,
  56. uint Flags
  57. );
  58. [DllImport("setupapi.dll", SetLastError = true)]
  59. private static extern bool SetupDiDestroyDeviceInfoList
  60. (
  61. IntPtr DeviceInfoSet
  62. );
  63. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  64. private static extern Boolean SetupDiEnumDeviceInterfaces(
  65. IntPtr hDevInfo,
  66. ref SP_DEVINFO_DATA devInfo,
  67. ref Guid interfaceClassGuid,
  68. UInt32 memberIndex,
  69. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData
  70. );
  71. // Alternate signature if you do not care about SP_DEVINFO_DATA and wish to pass NULL (IntPtr.Zero)
  72. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  73. private static extern Boolean SetupDiEnumDeviceInterfaces(
  74. IntPtr hDevInfo,
  75. IntPtr devInfo,
  76. ref Guid interfaceClassGuid,
  77. UInt32 memberIndex,
  78. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData
  79. );
  80. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  81. private static extern Boolean SetupDiGetDeviceInterfaceDetail(
  82. IntPtr hDevInfo,
  83. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
  84. ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
  85. UInt32 deviceInterfaceDetailDataSize,
  86. out UInt32 requiredSize,
  87. ref SP_DEVINFO_DATA deviceInfoData
  88. );
  89. // Alternate signature if you do not care about SP_DEVINFO_DATA and wish to pass NULL (IntPtr.Zero)
  90. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  91. private static extern Boolean SetupDiGetDeviceInterfaceDetail(
  92. IntPtr hDevInfo,
  93. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
  94. ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
  95. UInt32 deviceInterfaceDetailDataSize,
  96. out UInt32 requiredSize,
  97. IntPtr deviceInfoData
  98. );
  99. // Alternate signature - first call (we wish to pass IntPtr instead of reference to SP_DEVICE_INTERFACE_DETAIL_DATA)
  100. [DllImport(@"setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
  101. private static extern Boolean SetupDiGetDeviceInterfaceDetail(
  102. IntPtr hDevInfo,
  103. ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
  104. IntPtr deviceInterfaceDetailData,
  105. UInt32 deviceInterfaceDetailDataSize,
  106. out UInt32 requiredSize,
  107. IntPtr deviceInfoData
  108. );
  109. /// <summary>
  110. /// returns a handle to a device information set that contains requested device information elements.
  111. ///
  112. /// The caller must delete the returned device information set when it is no longer needed
  113. /// by calling DestroyDeviceInfoList().
  114. /// </summary>
  115. // http://msdn.microsoft.com/en-us/library/windows/hardware/ff551069%28v=vs.85%29.aspx
  116. public static IntPtr GetClassDevices(Guid classGuid)
  117. {
  118. uint flags = (uint)(DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE); // Only Devices present & Interface class
  119. IntPtr hDevInfo = SetupDiGetClassDevs(ref classGuid, IntPtr.Zero, IntPtr.Zero, flags);
  120. if (hDevInfo.ToInt64() == INVALID_HANDLE_VALUE)
  121. {
  122. int errorCode = Marshal.GetLastWin32Error();
  123. string message = String.Format("Unable to retrieve class devices, Win32 Error: {0}", errorCode);
  124. throw new IOException(message);
  125. }
  126. else
  127. {
  128. return hDevInfo;
  129. }
  130. }
  131. public static void DestroyDeviceInfoList(IntPtr hDevInfo)
  132. {
  133. bool success = DeviceInterfaceUtils.SetupDiDestroyDeviceInfoList(hDevInfo);
  134. if (!success)
  135. {
  136. int errorCode = Marshal.GetLastWin32Error();
  137. string message = String.Format("Unable to destroy device info list, Win32 Error: {0}", errorCode);
  138. throw new IOException(message);
  139. }
  140. }
  141. // http://msdn.microsoft.com/en-us/library/windows/hardware/ff551120%28v=vs.85%29.aspx
  142. public static SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceDetail(IntPtr hDevInfo, SP_DEVICE_INTERFACE_DATA deviceInterfaceData)
  143. {
  144. // For ERROR_INVALID_USER_BUFFER error see:
  145. // http://msdn.microsoft.com/en-us/library/windows/hardware/ff552343%28v=vs.85%29.aspx
  146. // http://stackoverflow.com/questions/10728644/properly-declare-sp-device-interface-detail-data-for-pinvoke
  147. uint requiredSize;
  148. SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
  149. bool success = SetupDiGetDeviceInterfaceDetail(hDevInfo, ref deviceInterfaceData, IntPtr.Zero, 0, out requiredSize, IntPtr.Zero);
  150. if (!success)
  151. {
  152. int errorCode = Marshal.GetLastWin32Error();
  153. if (errorCode == (int)Win32Error.ERROR_INSUFFICIENT_BUFFER)
  154. {
  155. uint size = requiredSize;
  156. // cbSize should parallel to sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA) in C
  157. // cbSize is calculated as sizeof(DWORD) + padding + sizeof(TCHAR) + padding
  158. int cbSize;
  159. if (IntPtr.Size == 4)
  160. {
  161. cbSize = sizeof(uint) + Marshal.SystemDefaultCharSize;
  162. }
  163. else
  164. {
  165. // take x64 padding into account
  166. cbSize = sizeof(uint) + 4;
  167. }
  168. IntPtr lpOutBuffer = Marshal.AllocHGlobal((int)size);
  169. Marshal.WriteInt32(lpOutBuffer, cbSize);
  170. success = SetupDiGetDeviceInterfaceDetail(hDevInfo, ref deviceInterfaceData, lpOutBuffer, size, out requiredSize, IntPtr.Zero);
  171. deviceInterfaceDetailData = (SP_DEVICE_INTERFACE_DETAIL_DATA)Marshal.PtrToStructure(lpOutBuffer, typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
  172. Marshal.FreeHGlobal(lpOutBuffer);
  173. if (!success)
  174. {
  175. errorCode = Marshal.GetLastWin32Error();
  176. string message = String.Format("Unable to retrieve device interface detail data, Win32 Error: {0}", errorCode);
  177. throw new IOException(message);
  178. }
  179. }
  180. else
  181. {
  182. errorCode = Marshal.GetLastWin32Error();
  183. string message = String.Format("Unable to retrieve device interface detail data, Win32 Error: {0}", errorCode);
  184. throw new IOException(message);
  185. }
  186. }
  187. return deviceInterfaceDetailData;
  188. }
  189. // Great C++ Example of enumerating and locating specific attach storage devices:
  190. // http://code.msdn.microsoft.com/windowshardware/CppStorageEnum-90ad5fa9
  191. public static List<string> GetDevicePathList(Guid deviceClassGuid)
  192. {
  193. IntPtr hDevInfo = GetClassDevices(deviceClassGuid);
  194. SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
  195. deviceInterfaceData.cbSize = (uint)Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DATA));
  196. uint index = 0;
  197. List<string> result = new List<string>();
  198. while (true)
  199. {
  200. bool success = DeviceInterfaceUtils.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref deviceClassGuid, index, ref deviceInterfaceData);
  201. if (!success)
  202. {
  203. int errorCode = Marshal.GetLastWin32Error();
  204. if (errorCode == (int)Win32Error.ERROR_NO_MORE_ITEMS)
  205. {
  206. break;
  207. }
  208. else
  209. {
  210. string message = String.Format("Unable to enumerate device interfaces, Win32 Error: {0}", errorCode);
  211. throw new IOException(message);
  212. }
  213. }
  214. SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = DeviceInterfaceUtils.GetDeviceInterfaceDetail(hDevInfo, deviceInterfaceData);
  215. result.Add(deviceInterfaceDetailData.DevicePath);
  216. index++;
  217. }
  218. DestroyDeviceInfoList(hDevInfo);
  219. return result;
  220. }
  221. }
  222. }