/Development/AlphaFS/Filesystem/NativeMethods.cs

http://alphafs.codeplex.com · C# · 2051 lines · 639 code · 276 blank · 1136 comment · 40 complexity · f0bc28e275fbb7a20f6c1c35e70d8c88 MD5 · raw file

Large files are truncated click here to view the full file

  1. /* Copyright (c) 2008-2012 Peter Palotas, Alexandr Normuradov
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to deal
  5. * in the Software without restriction, including without limitation the rights
  6. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. * copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. * THE SOFTWARE.
  20. */
  21. using System;
  22. using System.Diagnostics.CodeAnalysis;
  23. using System.Globalization;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Runtime.InteropServices;
  27. using System.Security.AccessControl;
  28. using System.Text;
  29. using Alphaleonis.Win32.Security;
  30. using Microsoft.Win32.SafeHandles;
  31. using SecurityNativeMethods = Alphaleonis.Win32.Security.NativeMethods;
  32. namespace Alphaleonis.Win32.Filesystem
  33. {
  34. internal static class NativeMethods
  35. {
  36. #region Internal Utility
  37. internal static uint GetLowOrderDword(long lowPart)
  38. {
  39. return (uint)(lowPart & 0xFFFFFFFF);
  40. }
  41. internal static uint GetHighOrderDword(long highPart)
  42. {
  43. return (uint)((highPart >> 32) & 0xFFFFFFFF);
  44. }
  45. internal static long ToLong(uint highPart, uint lowPart)
  46. {
  47. return (((long)highPart) << 32) | (((long)lowPart) & 0xFFFFFFFF);
  48. }
  49. internal static ulong LuidToLong(SecurityNativeMethods.Luid luid)
  50. {
  51. ulong high = (((ulong)luid.HighPart) << 32);
  52. ulong low = (((ulong)luid.LowPart) & 0x00000000FFFFFFFF);
  53. return high | low;
  54. }
  55. internal static SecurityNativeMethods.Luid LongToLuid(ulong lluid)
  56. {
  57. return new SecurityNativeMethods.Luid { HighPart = (uint)(lluid >> 32), LowPart = (uint)(lluid & 0xFFFFFFFF) };
  58. }
  59. internal static bool ContainsFileAttributesFlag(FileAttributes attributes, FileAttributes hasAttribute)
  60. {
  61. return (attributes & hasAttribute) == hasAttribute;
  62. }
  63. internal static bool ContainsFileSystemAttributesFlag(VolumeInfoAttributes attributes, VolumeInfoAttributes hasAttribute)
  64. {
  65. return (attributes & hasAttribute) == hasAttribute;
  66. }
  67. /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
  68. /// <param name="handle">The current handle to check.</param>
  69. /// <param name="throwException"><c>true</c> will throw an <exception cref="Resources.HandleInvalid"/>, <c>false</c> will not raise this exception..</param>
  70. /// <returns><c>true</c> on success, <c>false</c> otherwise.</returns>
  71. internal static bool IsValidHandle(SafeHandle handle, bool throwException = true)
  72. {
  73. if (handle == null || handle.IsClosed || handle.IsInvalid)
  74. {
  75. if (throwException)
  76. throw new ArgumentException(Resources.HandleInvalid);
  77. return false;
  78. }
  79. return true;
  80. }
  81. /// <summary>Check is the current stream is not null, not closed and not invalid.</summary>
  82. /// <param name="stream">The current stream to check.</param>
  83. /// <param name="throwException"><c>true</c> will throw an <exception cref="Resources.HandleInvalid"/>, <c>false</c> will not raise this exception.</param>
  84. /// <returns><c>true</c> on success, <c>false</c> otherwise.</returns>
  85. internal static bool IsValidStream(FileStream stream, bool throwException = true)
  86. {
  87. if (stream == null || stream.SafeFileHandle == null || stream.SafeFileHandle.IsClosed || stream.SafeFileHandle.IsInvalid)
  88. {
  89. if (throwException)
  90. throw new ArgumentException(Resources.StreamInvalid);
  91. return false;
  92. }
  93. return true;
  94. }
  95. #region UnitSizeToText
  96. /// <summary>Convert a number of type T to string with UnitSize or Percentage suffixed.</summary>
  97. internal static string UnitSizeToText<T>(T numberOfBytes, params bool[] options)
  98. {
  99. // Suffixes
  100. // bool[0] = false = "MB", True = "MiB"
  101. // bool[1] = true = %
  102. bool useMebi = options != null && options.Any() && options[0];
  103. bool usePercent = options != null && options.Count() == 2 && options[1];
  104. string template = "{0:0.00}{1}";
  105. string sfx = useMebi ? "Bi" : "bytes";
  106. double bytes = Convert.ToDouble(numberOfBytes, CultureInfo.InvariantCulture);
  107. if (bytes >= 1125899906842624) { sfx = useMebi ? "PiB" : "PB"; bytes /= 1125899906842624; }
  108. else if (bytes >= 1099511627776) { sfx = useMebi ? "TiB" : "TB"; bytes /= 1099511627776; }
  109. else if (bytes >= 1073741824) { sfx = useMebi ? "GiB" : "GB"; bytes /= 1073741824; }
  110. else if (bytes >= 1048576) { sfx = useMebi ? "MiB" : "MB"; bytes /= 1048576; }
  111. else if (bytes >= 1024) { sfx = useMebi ? "KiB" : "KB"; bytes /= 1024; }
  112. else if (!usePercent)
  113. // Will return "512 bytes" instead of "512,00 bytes".
  114. template = "{0:0}{1}";
  115. return string.Format(CultureInfo.CurrentCulture, template, bytes, usePercent ? "%" : " " + sfx);
  116. }
  117. /// <summary>Calculates a percentage value.</summary>
  118. /// <param name="currentValue"></param>
  119. /// <param name="minimumValue"></param>
  120. /// <param name="maximumValue"></param>
  121. internal static double PercentCalculate(double currentValue, double minimumValue, double maximumValue)
  122. {
  123. return (currentValue < 0 || maximumValue <= 0) ? 0 : currentValue * 100 / (maximumValue - minimumValue);
  124. }
  125. #endregion // UnitSizeToText
  126. #region SetErrorMode
  127. /// <summary>Controls whether the system will handle the specified types of serious errors or whether the process will handle them.</summary>
  128. /// <remarks>Not yet implemented: Windows 7, callers should favor SetThreadErrorMode over SetErrorMode since it is less disruptive to the normal behavior of the system.</remarks>
  129. /// <remarks>Minimum supported client: Windows 2000 Professional</remarks>
  130. /// <remarks>Minimum supported server: Windows 2000 Server</remarks>
  131. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  132. internal struct ChangeErrorMode : IDisposable
  133. {
  134. private readonly NativeErrorMode _oldMode;
  135. internal ChangeErrorMode(NativeErrorMode mode)
  136. {
  137. _oldMode = SetErrorMode(mode);
  138. }
  139. void IDisposable.Dispose()
  140. {
  141. SetErrorMode(_oldMode);
  142. }
  143. }
  144. /// <summary>Controls whether the system will handle the specified types of serious errors or whether the process will handle them.</summary>
  145. /// <returns>The return value is the previous state of the error-mode bit attributes.</returns>
  146. /// <remarks>
  147. /// Because the error mode is set for the entire process, you must ensure that multi-threaded applications
  148. /// do not set different error-mode attributes. Doing so can lead to inconsistent error handling.
  149. /// </remarks>
  150. /// <remarks>SetLastError is set to false.</remarks>
  151. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  152. [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)]
  153. [return: MarshalAs(UnmanagedType.U4)]
  154. private static extern NativeErrorMode SetErrorMode(NativeErrorMode nativeErrorMode);
  155. #endregion // SetErrorMode
  156. #region Platform
  157. #region HasFunction
  158. /// <summary>Functions to check if a specific Win32 API function is available to differentiate between "Windows XP / Windows 2003 Server" and "Windows Vista / Windows 2008 Server" platforms.</summary>
  159. /// <returns>true if the function exists; otherwise, false. To get extended error information, call GetLastError.</returns>
  160. internal static bool HasFunction(string dllName, string functionName)
  161. {
  162. IntPtr dll = LoadLibrary(dllName);
  163. if (dll == IntPtr.Zero)
  164. return false;
  165. IntPtr result = GetProcAddress(dll, functionName);
  166. return result != IntPtr.Zero && Marshal.GetLastWin32Error() != Win32Errors.ERROR_PROC_NOT_FOUND;
  167. }
  168. #endregion // HasFunction
  169. #region LoadLibrary
  170. /// <summary>Loads the specified module into the address space of the calling process. The specified module may cause other modules to be loaded.</summary>
  171. /// <returns>
  172. /// If the function succeeds, the return value is a handle to the module.
  173. /// If the function fails, the return value is <see langword="null"/>.
  174. /// </returns>
  175. /// <remarks>Minimum supported client: Windows 2000 Professional</remarks>
  176. /// <remarks>Minimum supported server: Windows 2000 Server</remarks>
  177. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  178. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "LoadLibraryW")]
  179. private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPWStr)] string lpFileName);
  180. #endregion // LoadLibrary
  181. #region GetProcAddress
  182. /// <summary>Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL).</summary>
  183. /// <returns>
  184. /// If the function succeeds, the return value is the address of the exported function or variable.
  185. /// If the function fails, the return value is <see langword="null"/>.
  186. /// </returns>
  187. /// <remarks>Minimum supported client: Windows 2000 Professional</remarks>
  188. /// <remarks>Minimum supported server: Windows 2000 Server</remarks>
  189. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  190. [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "1", Justification = "Stil need to investigate if CharSet.Unicode will not break this.")]
  191. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetProcAddress")]
  192. private static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string procName);
  193. // Note: Leave as: UnmanagedType.LPStr, using UnmanagedType.LPWStr yields no results.
  194. #endregion // GetProcAddress
  195. #endregion // Platform
  196. #endregion // Internal Utility
  197. #region Constants
  198. #region Standard Values
  199. /// <summary>MaxPath = 260
  200. /// The specified path, file name, or both exceed the system-defined maximum length.
  201. /// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
  202. /// </summary>
  203. internal const int MaxPath = 260;
  204. /// <summary>MaxPathUnicode = 32767</summary>
  205. internal const int MaxPathUnicode = 32767;
  206. /// <summary>DefaultFileEncoding = Encoding.UTF8; Default type of Encoding used for reading and writing files.</summary>
  207. internal static readonly Encoding DefaultFileEncoding = Encoding.UTF8;
  208. /// <summary>DefaultFileBufferSize = 4096; Default type buffer size used for reading and writing files.</summary>
  209. internal const int DefaultFileBufferSize = 4096;
  210. /// <summary>Combination of <see cref="CopyOptions.FailIfExists"/> and <see cref="CopyOptions.NoBuffering"/></summary>
  211. internal const CopyOptions CopyOptsFail = CopyOptions.FailIfExists | CopyOptions.NoBuffering;
  212. /// <summary>Combination of <see cref="CopyOptions.None"/> and <see cref="CopyOptions.NoBuffering"/></summary>
  213. internal const CopyOptions CopyOptsNone = CopyOptions.None | CopyOptions.NoBuffering;
  214. /// <summary>Combination of <see cref="MoveOptions.ReplaceExisting"/> and <see cref="MoveOptions.CopyAllowed"/></summary>
  215. internal const MoveOptions MoveOptsReplace = MoveOptions.ReplaceExisting | MoveOptions.CopyAllowed;
  216. #endregion // Standard Values
  217. #region Dos Device Flags (Used by DefineDosDevice)
  218. // 2012-01-31: Yomodo; Moved to: Filesystem\Enumerations\DosDeviceAttributes.cs as DosDeviceAttributes enum
  219. // Used by DefineDosDevice
  220. //internal const uint DDD_RAW_TARGET_PATH = 0x00000001;
  221. //internal const uint DDD_REMOVE_DEFINITION = 0x00000002;
  222. //internal const uint DDD_EXACT_MATCH_ON_REMOVE = 0x00000004;
  223. //internal const uint DDD_NO_BROADCAST_SYSTEM = 0x00000008;
  224. #endregion // Dos Device Flags (Used by DefineDosDevice)
  225. #region File System Flags (Used by GetVolumeInformation)
  226. // 2012-02-14: Yomodo; Moved to Filesystem\Enumerations\VolumeInfoAttributes.cs as VolumeInfoAttributes enum
  227. // Used by GetVolumeInformation
  228. //internal const uint FILE_CASE_SENSITIVE_SEARCH = 0x00000001;
  229. //internal const uint FILE_CASE_PRESERVED_NAMES = 0x00000002;
  230. //internal const uint FILE_UNICODE_ON_DISK = 0x00000004;
  231. //internal const uint FILE_PERSISTENT_ACLS = 0x00000008;
  232. //internal const uint FILE_FILE_COMPRESSION = 0x00000010;
  233. //internal const uint FILE_VOLUME_QUOTAS = 0x00000020;
  234. //internal const uint FILE_SUPPORTS_SPARSE_FILES = 0x00000040;
  235. //internal const uint FILE_SUPPORTS_REPARSE_POINTS = 0x00000080;
  236. //internal const uint FILE_SUPPORTS_REMOTE_STORAGE = 0x00000100;
  237. //internal const uint FILE_VOLUME_IS_COMPRESSED = 0x00008000;
  238. //internal const uint FILE_SUPPORTS_OBJECT_IDS = 0x00010000;
  239. //internal const uint FILE_SUPPORTS_ENCRYPTION = 0x00020000;
  240. //internal const uint FILE_NAMED_STREAMS = 0x00040000;
  241. //internal const uint FILE_READ_ONLY_VOLUME = 0x00080000;
  242. #endregion // File System Flags (Used by GetVolumeInformation)
  243. #region Drive Types (Used by GetDriveType)
  244. // 2012-02-14: Yomodo; Obsolete, .NET DriveType enum is used instead.
  245. //internal const uint DRIVE_UNKNOWN = 0;
  246. //internal const uint DRIVE_NO_ROOT_DIR = 1;
  247. //internal const uint DRIVE_REMOVABLE = 2;
  248. //internal const uint DRIVE_FIXED = 3;
  249. //internal const uint DRIVE_REMOTE = 4;
  250. //internal const uint DRIVE_CDROM = 5;
  251. //internal const uint DRIVE_RAMDISK = 6;
  252. #endregion // Drive Types (Used by GetDriveType)
  253. #region File Access and Rights
  254. // 2012-01-31: Yomodo; Moved to: Filesystem\Enumerations\FileSystemRights.cs as FileSystemRights enum
  255. // 2012-10-10: Yomodo; .NET already provides this enum.
  256. //internal const uint DRIVE_UNKNOWN = 0;
  257. //public const uint ACCESS_SYSTEM_SECURITY = 0x01000000;
  258. //public const uint DELETE = 0x00010000;
  259. //public const uint READ_CONTROL = 0x00020000;
  260. //public const uint WRITE_DAC = 0x00040000;
  261. //public const uint WRITE_OWNER = 0x00080000;
  262. //public const uint SYNCHRONIZE = 0x00100000;
  263. //public const uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
  264. //public const uint STANDARD_RIGHTS_READ = READ_CONTROL;
  265. //public const uint STANDARD_RIGHTS_WRITE = READ_CONTROL;
  266. //public const uint STANDARD_RIGHTS_EXECUTE = READ_CONTROL;
  267. //public const uint STANDARD_RIGHTS_ALL = 0x001F0000;
  268. //public const uint SPECIFIC_RIGHTS_ALL = 0x0000FFFF;
  269. //public const uint FILE_READ_DATA = 0x0001;
  270. //public const uint FILE_LIST_DIRECTORY = 0x0001;
  271. //public const uint FILE_WRITE_DATA = 0x0002;
  272. //public const uint FILE_ADD_FILE = 0x0002;
  273. //public const uint FILE_APPEND_DATA = 0x0004;
  274. //public const uint FILE_ADD_SUBDIRECTORY = 0x0004;
  275. //public const uint FILE_CREATE_PIPE_INSTANCE = 0x0004;
  276. //public const uint FILE_READ_EA = 0x0008;
  277. //public const uint FILE_WRITE_EA = 0x0010;
  278. //public const uint FILE_EXECUTE = 0x0020;
  279. //public const uint FILE_TRAVERSE = 0x0020;
  280. //public const uint FILE_DELETE_CHILD = 0x0040;
  281. //public const uint FILE_READ_ATTRIBUTES = 0x0080;
  282. //public const uint FILE_WRITE_ATTRIBUTES = 0x0100;
  283. //public const uint FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF;
  284. //public const uint FILE_GENERIC_READ = STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE;
  285. //public const uint FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE;
  286. //public const uint FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE;
  287. //public const uint FILE_SHARE_READ = 0x00000001;
  288. //public const uint FILE_SHARE_WRITE = 0x00000002;
  289. //public const uint FILE_SHARE_DELETE = 0x00000004;
  290. //public const uint FILE_ATTRIBUTE_READONLY = 0x00000001;
  291. //public const uint FILE_ATTRIBUTE_HIDDEN = 0x00000002;
  292. //public const uint FILE_ATTRIBUTE_SYSTEM = 0x00000004;
  293. //public const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
  294. //public const uint FILE_ATTRIBUTE_ARCHIVE = 0x00000020;
  295. //public const uint FILE_ATTRIBUTE_DEVICE = 0x00000040;
  296. //public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;
  297. //public const uint FILE_ATTRIBUTE_TEMPORARY = 0x00000100;
  298. //public const uint FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200;
  299. //public const uint FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400;
  300. //public const uint FILE_ATTRIBUTE_COMPRESSED = 0x00000800;
  301. //public const uint FILE_ATTRIBUTE_OFFLINE = 0x00001000;
  302. //public const uint FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000;
  303. //public const uint FILE_ATTRIBUTE_ENCRYPTED = 0x00004000;
  304. //public const uint FILE_ATTRIBUTE_VIRTUAL = 0x00010000;
  305. //public const uint FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001;
  306. //public const uint FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002;
  307. //public const uint FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004;
  308. //public const uint FILE_NOTIFY_CHANGE_SIZE = 0x00000008;
  309. //public const uint FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010;
  310. //public const uint FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020;
  311. //public const uint FILE_NOTIFY_CHANGE_CREATION = 0x00000040;
  312. //public const uint FILE_NOTIFY_CHANGE_SECURITY = 0x00000100;
  313. //public const uint FILE_ACTION_ADDED = 0x00000001;
  314. //public const uint FILE_ACTION_REMOVED = 0x00000002;
  315. //public const uint FILE_ACTION_MODIFIED = 0x00000003;
  316. //public const uint FILE_ACTION_RENAMED_OLD_NAME = 0x00000004;
  317. //public const uint FILE_ACTION_RENAMED_NEW_NAME = 0x00000005;
  318. //public const uint FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000;
  319. //public const uint FILE_SUPPORTS_TRANSACTIONS = 0x00200000;
  320. //public const uint REPLACEFILE_WRITE_THROUGH = 0x01;
  321. //public const uint REPLACEFILE_IGNORE_MERGE_ERRORS = 0x02;
  322. //public const uint REPLACEFILE_IGNORE_ACL_ERRORS = 0x04;
  323. #endregion // File Access and Rights
  324. #region Security
  325. // 2012-01-31: Yomodo; Moved to: Filesystem\Enumerations\SecurityInformation.cs as SecurityInformation enum
  326. //public const int OWNER_SECURITY_INFORMATION = 0x00000001;
  327. //public const int GROUP_SECURITY_INFORMATION = 0x00000002;
  328. //public const int DACL_SECURITY_INFORMATION = 0x00000004;
  329. //public const int SACL_SECURITY_INFORMATION = 0x00000008;
  330. /* Not needed?
  331. public const uint LABEL_SECURITY_INFORMATION = 0x00000010;
  332. public const uint PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000;
  333. public const uint PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000;
  334. public const uint UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000;
  335. public const uint UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000;
  336. */
  337. #endregion
  338. #region Backup
  339. // 2012-01-31: Yomodo; Moved to: Filesystem\Enumerations\BackupStream.cs as BackupStreamAttributes enum
  340. // (Only moved these values, enum already existed)
  341. //public const uint STREAM_NORMAL_ATTRIBUTE = 0x00000000;
  342. //public const uint STREAM_MODIFIED_WHEN_READ = 0x00000001;
  343. //public const uint STREAM_CONTAINS_SECURITY = 0x00000002;
  344. //public const uint STREAM_CONTAINS_PROPERTIES = 0x00000004;
  345. //public const uint STREAM_SPARSE_ATTRIBUTE = 0x00000008;
  346. #endregion
  347. #endregion // Constants
  348. #region Network
  349. // 2012-01-31: Yomodo; Moved to: Filesystem\Enumerations\RemoteNameInfo.cs as RemoteNameInfo enum
  350. //[StructLayout(LayoutKind.Sequential)]
  351. //internal struct UNIVERSAL_NAME_INFO
  352. //{
  353. // /// <summary>
  354. // /// Network share name string that identifies a network resource.
  355. // /// A network share path identifies a network resource in an unambiguous, computer-independent manner.
  356. // /// You can pass the path to processes on other computers, allowing those processes to obtain access to the network resource.
  357. // /// </summary>
  358. // public string universalName;
  359. //}
  360. //public const uint UNIVERSAL_NAME_INFO_LEVEL = 0x00000001;
  361. //public const uint REMOTE_NAME_INFO_LEVEL = 0x00000002;
  362. //[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  363. //internal struct UNIVERSAL_NAME_INFO
  364. //{
  365. // [MarshalAs(UnmanagedType.LPWStr)] public string universalName;
  366. //}
  367. /// <summary>The WNetGetUniversalName function takes a drive-based path for a network resource and returns an information structure that contains a more universal form of the name.</summary>
  368. /// <returns>
  369. /// If the function succeeds, the return value is <see cref="Win32Errors.NO_ERROR"/>
  370. /// If the function fails, the return value is a system error code, <see cref="Win32Errors"/>
  371. /// </returns>
  372. /// <remarks>Minimum supported client: Windows 2000 Professional</remarks>
  373. /// <remarks>Minimum supported server: Windows 2000 Server</remarks>
  374. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  375. [DllImport("mpr.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "WNetGetUniversalNameW")]
  376. [return: MarshalAs(UnmanagedType.U4)]
  377. internal static extern uint WNetGetUniversalName([MarshalAs(UnmanagedType.LPWStr)] string lpLocalPath, [MarshalAs(UnmanagedType.U4)] uint dwInfoLevel, SafeGlobalMemoryBufferHandle lpBuffer, [MarshalAs(UnmanagedType.U4)] out uint lpBufferSize);
  378. #endregion // Network
  379. #region Volume Management
  380. #region DosDevice
  381. /// <summary>Defines, redefines, or deletes MS-DOS device names.</summary>
  382. /// <returns>
  383. /// If the function succeeds, the return value is nonzero.
  384. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  385. /// To get extended error information call Win32Exception()
  386. /// </returns>
  387. /// <remarks>Minimum supported client: Windows XP</remarks>
  388. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  389. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  390. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DefineDosDeviceW")]
  391. [return: MarshalAs(UnmanagedType.Bool)]
  392. internal static extern bool DefineDosDevice(DosDeviceAttributes dwAttributes, [MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, [MarshalAs(UnmanagedType.LPWStr)] string lpTargetPath);
  393. /// <summary>Retrieves information about MS-DOS device names.</summary>
  394. /// <returns>
  395. /// If the function succeeds, the return value is nonzero.
  396. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  397. /// To get extended error information call Win32Exception()
  398. /// If the buffer is too small, the function fails and the last error code is ERROR_INSUFFICIENT_BUFFER.
  399. /// </returns>
  400. /// <remarks>
  401. /// Windows Server 2003 and Windows XP: QueryDosDevice first searches the Local MS-DOS Device namespace for the specified device name.
  402. /// If the device name is not found, the function will then search the Global MS-DOS Device namespace.
  403. /// </remarks>
  404. /// <remarks>Minimum supported client: Windows XP</remarks>
  405. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  406. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  407. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "QueryDosDeviceW")]
  408. [return: MarshalAs(UnmanagedType.U4)]
  409. internal static extern uint QueryDosDevice([MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, char[] lpTargetPath, [MarshalAs(UnmanagedType.U4)] uint ucchMax);
  410. #endregion // DosDevice
  411. #region Volume
  412. /// <summary>Retrieves the name of a volume on a computer. FindFirstVolume is used to begin scanning the volumes of a computer.</summary>
  413. /// <returns>
  414. /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolume and FindVolumeClose functions.
  415. /// If the function fails to find any volumes, the return value is the INVALID_HANDLE_VALUE error code. To get extended error information, call GetLastError.
  416. /// </returns>
  417. /// <remarks>Minimum supported client: Windows XP</remarks>
  418. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  419. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  420. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeW")]
  421. internal extern static SafeFindVolumeHandle FindFirstVolume(StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
  422. /// <summary>Retrieves the name of a mounted folder on the specified volume. FindFirstVolumeMountPoint is used to begin scanning the mounted folders on a volume.</summary>
  423. /// <returns>
  424. /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolumeMountPoint and FindVolumeMountPointClose functions.
  425. /// If the function fails to find a mounted folder on the volume, the return value is the INVALID_HANDLE_VALUE error code.
  426. /// </returns>
  427. /// <remarks>Minimum supported client: Windows XP</remarks>
  428. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  429. /// <remarks>"lpszRootPathName" must end with a trailing backslash.</remarks>
  430. /// <remarks>
  431. /// Might not enumerate all: http://blogs.msdn.com/b/seealso/archive/2011/07/27/use-this-not-this-apis-to-avoid-all-together.aspx
  432. /// After Windows Vista, the API has changed. The short version of the issue you may encounter with FindFirstVolumeMountPoint is that unless you have a superuser account and permissions to the share, the mount point will not show up in the list.
  433. /// Your enumerated lists of mount points can be incomplete and you will not know when listed folders require permissions.</remarks>
  434. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  435. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeMountPointW")]
  436. internal extern static SafeFindVolumeMountPointHandle FindFirstVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszRootPathName, StringBuilder lpszVolumeMountPoint, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
  437. /// <summary>Continues a volume search started by a call to the FindFirstVolume function. FindNextVolume finds one volume per call.</summary>
  438. /// <returns>
  439. /// If the function succeeds, the return value is nonzero.
  440. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. If no matching files can be found, the GetLastError function
  441. /// returns the ERROR_NO_MORE_FILES error code. In that case, close the search with the FindVolumeClose function.
  442. /// </returns>
  443. /// <remarks>Minimum supported client: Windows XP</remarks>
  444. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  445. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  446. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextVolumeW")]
  447. [return: MarshalAs(UnmanagedType.Bool)]
  448. internal extern static bool FindNextVolume(SafeHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
  449. /// <summary>Continues a mounted folder search started by a call to the FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one mounted folder per call.</summary>
  450. /// <returns>
  451. /// If the function succeeds, the return value is nonzero.
  452. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. If no more mounted folders can be found, the GetLastError function returns the ERROR_NO_MORE_FILES error code.
  453. /// In that case, close the search with the FindVolumeMountPointClose function.
  454. /// </returns>
  455. /// <remarks>Minimum supported client: Windows XP</remarks>
  456. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  457. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  458. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextVolumeMountPointW")]
  459. [return: MarshalAs(UnmanagedType.Bool)]
  460. internal extern static bool FindNextVolumeMountPoint(SafeHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
  461. /// <summary>Closes the specified volume search handle.</summary>
  462. /// <returns>
  463. /// If the function succeeds, the return value is nonzero.
  464. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  465. /// </returns>
  466. /// <remarks>Minimum supported client: Windows XP</remarks>
  467. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  468. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  469. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  470. [return: MarshalAs(UnmanagedType.Bool)]
  471. internal extern static bool FindVolumeClose(IntPtr hFindVolume);
  472. /// <summary>Closes the specified mounted folder search handle.</summary>
  473. /// <returns>
  474. /// If the function succeeds, the return value is nonzero.
  475. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  476. /// </returns>
  477. /// <remarks>Minimum supported client: Windows XP</remarks>
  478. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  479. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  480. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  481. [return: MarshalAs(UnmanagedType.Bool)]
  482. internal extern static bool FindVolumeMountPointClose(IntPtr hFindVolume);
  483. /// <summary>Retrieves a volume GUID path for the volume that is associated with the specified volume mount point (drive letter, volume GUID path, or mounted folder).</summary>
  484. /// <returns>
  485. /// If the function succeeds, the return value is nonzero.
  486. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  487. /// To get extended error information call Win32Exception()
  488. /// </returns>
  489. /// <remarks>Minimum supported client: Windows XP</remarks>
  490. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  491. /// <remarks>"lpszVolumeMountPoint" must end with a trailing backslash.</remarks>
  492. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  493. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeNameForVolumeMountPointW")]
  494. [return: MarshalAs(UnmanagedType.Bool)]
  495. public static extern bool GetVolumeNameForVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
  496. /// <summary>Retrieves the volume mount point where the specified path is mounted.</summary>
  497. /// <returns>
  498. /// If the function succeeds, the return value is nonzero.
  499. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  500. /// To get extended error information call Win32Exception()
  501. /// </returns>
  502. /// <remarks>Minimum supported client: Windows XP</remarks>
  503. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  504. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  505. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNameW")]
  506. [return: MarshalAs(UnmanagedType.Bool)]
  507. public static extern bool GetVolumePathName([MarshalAs(UnmanagedType.LPWStr)] string lpszFileName, StringBuilder lpszVolumePathName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength);
  508. /// <summary>Retrieves a list of drive letters and mounted folder paths for the specified volume.</summary>
  509. /// <returns>
  510. /// If the function succeeds, the return value is nonzero.
  511. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  512. /// </returns>
  513. /// <remarks>Minimum supported client: Windows XP</remarks>
  514. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  515. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  516. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNamesForVolumeNameW")]
  517. [return: MarshalAs(UnmanagedType.Bool)]
  518. public static extern bool GetVolumePathNamesForVolumeName([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, char[] lpszVolumePathNames, [MarshalAs(UnmanagedType.U4)] uint cchBuferLength, [MarshalAs(UnmanagedType.U4)] out uint lpcchReturnLength);
  519. /// <summary>Retrieves information about the file system and volume associated with the specified root directory.</summary>
  520. /// <returns>
  521. /// If all the requested information is retrieved, the return value is nonzero.
  522. /// If not all the requested information is retrieved, the return value is zero.
  523. /// </returns>
  524. /// <remarks>Minimum supported client: Windows XP</remarks>
  525. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  526. /// <remarks>"lpRootPathName" must end with a trailing backslash.</remarks>
  527. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  528. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationW")]
  529. [return: MarshalAs(UnmanagedType.Bool)]
  530. internal extern static bool GetVolumeInformation([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out uint lpMaximumComponentLength, [MarshalAs(UnmanagedType.U4)] out VolumeInfoAttributes lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize);
  531. /// <summary>Retrieves information about the file system and volume associated with the specified file.</summary>
  532. /// <returns>
  533. /// If all the requested information is retrieved, the return value is nonzero.
  534. /// If not all the requested information is retrieved, the return value is zero.
  535. /// To get extended error information call Win32Exception()
  536. /// </returns>
  537. /// <remarks>Minimum supported client: Windows Vista</remarks>
  538. /// <remarks>Minimum supported server: Windows Server 2008</remarks>
  539. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  540. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationByHandleW")]
  541. [return: MarshalAs(UnmanagedType.Bool)]
  542. internal extern static bool GetVolumeInformationByHandle(SafeHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out uint lpMaximumComponentLength, out VolumeInfoAttributes lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize);
  543. /// <summary>Sets the label of a file system volume.</summary>
  544. /// <returns>
  545. /// If the function succeeds, the return value is nonzero.
  546. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  547. /// </returns>
  548. /// <remarks>Minimum supported client: Windows XP</remarks>
  549. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  550. /// <remarks>"lpRootPathName" must end with a trailing backslash.</remarks>
  551. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  552. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetVolumeLabelW")]
  553. [return: MarshalAs(UnmanagedType.Bool)]
  554. internal extern static bool SetVolumeLabel([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, [MarshalAs(UnmanagedType.LPWStr)] string lpVolumeName);
  555. /// <summary>Associates a volume with a drive letter or a directory on another volume.</summary>
  556. /// <returns>
  557. /// If the function succeeds, the return value is nonzero.
  558. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  559. /// </returns>
  560. /// <remarks>Minimum supported client: Windows XP</remarks>
  561. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  562. /// <remarks>"lpszVolumeMountPoint" must end with a trailing backslash.</remarks>
  563. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  564. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetVolumeMountPointW")]
  565. [return: MarshalAs(UnmanagedType.Bool)]
  566. internal extern static bool SetVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, [MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName);
  567. /// <summary>Deletes a drive letter or mounted folder.</summary>
  568. /// If all the requested information is retrieved, the return value is nonzero.
  569. /// If not all the requested information is retrieved, the return value is zero.
  570. /// To get extended error information call Win32Exception()
  571. /// <remarks>Deleting a mounted folder does not cause the underlying directory to be deleted.
  572. /// It's not an error to attempt to unmount a volume from a volume mount point when there is no volume actually mounted at that volume mount point.
  573. /// </remarks>
  574. /// <remarks>Minimum supported client: Windows XP</remarks>
  575. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  576. /// <remarks>"lpszVolumeMountPoint" must end with a trailing backslash.</remarks>
  577. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  578. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeleteVolumeMountPointW")]
  579. [return: MarshalAs(UnmanagedType.Bool)]
  580. internal extern static bool DeleteVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint);
  581. #endregion // Volume
  582. #endregion // Volume Management
  583. #region Disk Management
  584. /// <summary>Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.</summary>
  585. /// <returns>The return value specifies the type of drive, which can be one of the following <see cref="DriveType"/> values.</returns>
  586. /// <remarks>Minimum supported client: Windows XP</remarks>
  587. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  588. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  589. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetDriveTypeW")]
  590. [return: MarshalAs(UnmanagedType.U4)]
  591. internal extern static DriveType GetDriveType([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName);
  592. /// <summary>Retrieves information about the specified disk, including the amount of free space on the disk.</summary>
  593. /// <returns>
  594. /// If the function succeeds, the return value is nonzero.
  595. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  596. /// </returns>
  597. /// <remarks>
  598. /// Symbolic link behavior; if the path points to a symbolic link, the operation is performed on the target.
  599. /// </remarks>
  600. /// <remarks>Minimum supported client: Windows XP</remarks>
  601. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  602. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  603. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetDiskFreeSpaceW")]
  604. [return: MarshalAs(UnmanagedType.Bool)]
  605. internal static extern bool GetDiskFreeSpace([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, out ulong lpSectorsPerCluster, out ulong lpBytesPerSector, out ulong lpNumberOfFreeClusters, out ulong lpTotalNumberOfClusters);
  606. /// <summary>Retrieves information about the amount of space that is available on a disk volume, which is the total amount of space,
  607. /// the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread.
  608. /// </summary>
  609. /// <returns>
  610. /// If the function succeeds, the return value is nonzero.
  611. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  612. /// </returns>
  613. /// <remarks>
  614. /// Symbolic link behavior; if the path points to a symbolic link, the operation is performed on the target.
  615. /// </remarks>
  616. /// <remarks>Minimum supported client: Windows XP</remarks>
  617. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  618. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  619. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetDiskFreeSpaceExW")]
  620. [return: MarshalAs(UnmanagedType.Bool)]
  621. internal static extern bool GetDiskFreeSpaceEx([MarshalAs(UnmanagedType.LPWStr)] string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes);
  622. /// <summary>Retrieves a bitmask representing the currently available disk drives.</summary>
  623. /// <returns>
  624. /// If the function succeeds, the return value is a bitmask representing the currently available disk drives.
  625. /// Bit position 0 (the least-significant bit) is drive A, bit position 1 is drive B, bit position 2 is drive C, and so on.
  626. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  627. /// </returns>
  628. /// <remarks>Minimum supported client: Windows XP</remarks>
  629. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  630. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  631. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  632. [return: MarshalAs(UnmanagedType.U4)]
  633. internal static extern uint GetLogicalDrives();
  634. #endregion // Disk Management
  635. #region Path
  636. #region GetLongPathName
  637. /// <summary>Converts the specified path to its long form.</summary>
  638. /// <returns>
  639. /// If the function succeeds, the return value is nonzero.
  640. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  641. /// </returns>
  642. /// <remarks>Minimum supported client: Windows XP</remarks>
  643. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  644. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  645. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetLongPathNameW")]
  646. [return: MarshalAs(UnmanagedType.U4)]
  647. internal static extern uint GetLongPathName([MarshalAs(UnmanagedType.LPWStr)] string lpszShortPath, StringBuilder lpszLongPath, [MarshalAs(UnmanagedType.U4)] uint cchBuffer);
  648. #endregion // GetLongPathName
  649. #region GetShortPathName
  650. /// <summary>Retrieves the short path form of the specified path.</summary>
  651. /// <returns>
  652. /// If the function succeeds, the return value is nonzero.
  653. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  654. /// </returns>
  655. /// <remarks>Minimum supported client: Windows XP</remarks>
  656. /// <remarks>Minimum supported server: Windows Server 2003</remarks>
  657. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  658. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetShortPathNameW")]
  659. [return: MarshalAs(UnmanagedType.U4)]
  660. internal static extern uint GetShortPathName([MarshalAs(UnmanagedType.LPWStr)] string lpszLongPath, StringBuilder lpszShortPath, [MarshalAs(UnmanagedType.U4)] uint cchBuffer);
  661. #endregion // GetShortPathName
  662. #region Path/Url Conversion
  663. /// <summary>Converts a file URL to a Microsoft MS-DOS path.</summary>
  664. /// <returns>Type: HRESULT
  665. /// If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
  666. /// </returns>
  667. /// <remarks>Minimum supported client: Windows 2000 Professional</remarks>
  668. /// <remarks>Minimum supported server: Windows 2000 Server</remarks>
  669. /// <remarks>This function returns a standard COM error value, so set "PreserveSig" to <see langref="false"/> to automatically convert HRESULT or retval values to exceptions.</remarks>
  670. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  671. [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "PathCreateFromUrlW", PreserveSig = false)]
  672. [return: MarshalAs(UnmanagedType.U4)]
  673. internal static extern uint PathCreateFromUrl([MarshalAs(UnmanagedType.LPWStr)] string pszUrl, StringBuilder pszPath, ref uint pcchPath, uint dwFlags);
  674. /// <summary>Creates a path from a file URL.</summary>
  675. /// <returns>Type: HRESULT
  676. /// If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
  677. /// </returns>
  678. /// <remarks>Minimum supported client: Windows Vista</remarks>
  679. /// <remarks>Minimum supported server: Windows Server 2008</remarks>
  680. /// <remarks>This function returns a standard COM error value, so set "PreserveSig" to <see langref="false"/> to automatically convert HRESULT or retval values to exceptions.</remarks>
  681. [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")]
  682. [DllImport("shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode, PreserveSig = false)]
  683. [return: MarshalAs(UnmanagedType.U4)]
  684. internal static extern uint PathCreateFromUrlAlloc([MarshalAs(UnmanagedType.LPWStr)] string pszIn, out StringBuilder pszPath, uint dwFlags);
  685. /// <summary>Converts a Microsoft MS-DOS path to a canonicalized URL.</summary>
  686. /// <returns>Type: HRESULT
  687. /// Returns S_FALSE if pszPath is already in URL format. In this case, pszPath will simply be copied to ps…