Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

418 lignes
22 KiB

  1. /* Copyright (C) 2008-2016 Peter Palotas, Jeffrey Jangli, 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.Runtime.InteropServices;
  26. using System.Security;
  27. namespace Alphaleonis.Win32.Filesystem
  28. {
  29. partial class Directory
  30. {
  31. #region .NET
  32. /// <summary>Deletes an empty directory from a specified path.</summary>
  33. /// <exception cref="ArgumentException"/>
  34. /// <exception cref="ArgumentNullException"/>
  35. /// <exception cref="DirectoryNotFoundException"/>
  36. /// <exception cref="IOException"/>
  37. /// <exception cref="NotSupportedException"/>
  38. /// <exception cref="UnauthorizedAccessException"/>
  39. /// <exception cref="DirectoryReadOnlyException"/>
  40. /// <param name="path">The name of the empty directory to remove. This directory must be writable and empty.</param>
  41. [SecurityCritical]
  42. public static void Delete(string path)
  43. {
  44. DeleteDirectoryCore(null, null, path, false, false, true, false, PathFormat.RelativePath);
  45. }
  46. /// <summary>Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
  47. /// <exception cref="ArgumentException"/>
  48. /// <exception cref="ArgumentNullException"/>
  49. /// <exception cref="DirectoryNotFoundException"/>
  50. /// <exception cref="IOException"/>
  51. /// <exception cref="NotSupportedException"/>
  52. /// <exception cref="UnauthorizedAccessException"/>
  53. /// <exception cref="DirectoryReadOnlyException"/>
  54. /// <param name="path">The name of the directory to remove.</param>
  55. /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param>
  56. [SecurityCritical]
  57. public static void Delete(string path, bool recursive)
  58. {
  59. DeleteDirectoryCore(null, null, path, recursive, false, !recursive, false, PathFormat.RelativePath);
  60. }
  61. #endregion // .NET
  62. /// <summary>[AlphaFS] Deletes an empty directory from a specified path.</summary>
  63. /// <exception cref="ArgumentException"/>
  64. /// <exception cref="ArgumentNullException"/>
  65. /// <exception cref="DirectoryNotFoundException"/>
  66. /// <exception cref="IOException"/>
  67. /// <exception cref="NotSupportedException"/>
  68. /// <exception cref="UnauthorizedAccessException"/>
  69. /// <exception cref="DirectoryReadOnlyException"/>
  70. /// <param name="path">The name of the empty directory to remove. This directory must be writable and empty.</param>
  71. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  72. [SecurityCritical]
  73. public static void Delete(string path, PathFormat pathFormat)
  74. {
  75. DeleteDirectoryCore(null, null, path, false, false, true, false, pathFormat);
  76. }
  77. /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
  78. /// <exception cref="ArgumentException"/>
  79. /// <exception cref="ArgumentNullException"/>
  80. /// <exception cref="DirectoryNotFoundException"/>
  81. /// <exception cref="IOException"/>
  82. /// <exception cref="NotSupportedException"/>
  83. /// <exception cref="UnauthorizedAccessException"/>
  84. /// <exception cref="DirectoryReadOnlyException"/>
  85. /// <param name="path">The name of the directory to remove.</param>
  86. /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param>
  87. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  88. [SecurityCritical]
  89. public static void Delete(string path, bool recursive, PathFormat pathFormat)
  90. {
  91. DeleteDirectoryCore(null, null, path, recursive, false, !recursive, false, pathFormat);
  92. }
  93. /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
  94. /// <exception cref="ArgumentException"/>
  95. /// <exception cref="ArgumentNullException"/>
  96. /// <exception cref="DirectoryNotFoundException"/>
  97. /// <exception cref="IOException"/>
  98. /// <exception cref="NotSupportedException"/>
  99. /// <exception cref="UnauthorizedAccessException"/>
  100. /// <exception cref="DirectoryReadOnlyException"/>
  101. /// <param name="path">The name of the directory to remove.</param>
  102. /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param>
  103. /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only <see cref="FileAttributes"/> of files and directories.</param>
  104. [SecurityCritical]
  105. public static void Delete(string path, bool recursive, bool ignoreReadOnly)
  106. {
  107. DeleteDirectoryCore(null, null, path, recursive, ignoreReadOnly, !recursive, false, PathFormat.RelativePath);
  108. }
  109. /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
  110. /// <exception cref="ArgumentException"/>
  111. /// <exception cref="ArgumentNullException"/>
  112. /// <exception cref="DirectoryNotFoundException"/>
  113. /// <exception cref="IOException"/>
  114. /// <exception cref="NotSupportedException"/>
  115. /// <exception cref="UnauthorizedAccessException"/>
  116. /// <exception cref="DirectoryReadOnlyException"/>
  117. /// <param name="path">The name of the directory to remove.</param>
  118. /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param>
  119. /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only <see cref="FileAttributes"/> of files and directories.</param>
  120. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  121. [SecurityCritical]
  122. public static void Delete(string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat)
  123. {
  124. DeleteDirectoryCore(null, null, path, recursive, ignoreReadOnly, !recursive, false, pathFormat);
  125. }
  126. #region Transactional
  127. /// <summary>[AlphaFS] Deletes an empty directory from a specified path.</summary>
  128. /// <exception cref="ArgumentException"/>
  129. /// <exception cref="ArgumentNullException"/>
  130. /// <exception cref="DirectoryNotFoundException"/>
  131. /// <exception cref="IOException"/>
  132. /// <exception cref="NotSupportedException"/>
  133. /// <exception cref="UnauthorizedAccessException"/>
  134. /// <exception cref="DirectoryReadOnlyException"/>
  135. /// <param name="transaction">The transaction.</param>
  136. /// <param name="path">The name of the empty directory to remove. This directory must be writable and empty.</param>
  137. [SecurityCritical]
  138. public static void DeleteTransacted(KernelTransaction transaction, string path)
  139. {
  140. DeleteDirectoryCore(null, transaction, path, false, false, true, false, PathFormat.RelativePath);
  141. }
  142. /// <summary>[AlphaFS] Deletes an empty directory from a specified path.</summary>
  143. /// <exception cref="ArgumentException"/>
  144. /// <exception cref="ArgumentNullException"/>
  145. /// <exception cref="DirectoryNotFoundException"/>
  146. /// <exception cref="IOException"/>
  147. /// <exception cref="NotSupportedException"/>
  148. /// <exception cref="UnauthorizedAccessException"/>
  149. /// <exception cref="DirectoryReadOnlyException"/>
  150. /// <param name="transaction">The transaction.</param>
  151. /// <param name="path">The name of the empty directory to remove. This directory must be writable and empty.</param>
  152. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  153. [SecurityCritical]
  154. public static void DeleteTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
  155. {
  156. DeleteDirectoryCore(null, transaction, path, false, false, true, false, pathFormat);
  157. }
  158. /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
  159. /// <exception cref="ArgumentException"/>
  160. /// <exception cref="ArgumentNullException"/>
  161. /// <exception cref="DirectoryNotFoundException"/>
  162. /// <exception cref="IOException"/>
  163. /// <exception cref="NotSupportedException"/>
  164. /// <exception cref="UnauthorizedAccessException"/>
  165. /// <exception cref="DirectoryReadOnlyException"/>
  166. /// <param name="transaction">The transaction.</param>
  167. /// <param name="path">The name of the directory to remove.</param>
  168. /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param>
  169. [SecurityCritical]
  170. public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive)
  171. {
  172. DeleteDirectoryCore(null, transaction, path, recursive, false, !recursive, false, PathFormat.RelativePath);
  173. }
  174. /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
  175. /// <exception cref="ArgumentException"/>
  176. /// <exception cref="ArgumentNullException"/>
  177. /// <exception cref="DirectoryNotFoundException"/>
  178. /// <exception cref="IOException"/>
  179. /// <exception cref="NotSupportedException"/>
  180. /// <exception cref="UnauthorizedAccessException"/>
  181. /// <exception cref="DirectoryReadOnlyException"/>
  182. /// <param name="transaction">The transaction.</param>
  183. /// <param name="path">The name of the directory to remove.</param>
  184. /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param>
  185. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  186. [SecurityCritical]
  187. public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, PathFormat pathFormat)
  188. {
  189. DeleteDirectoryCore(null, transaction, path, recursive, false, !recursive, false, pathFormat);
  190. }
  191. /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
  192. /// <exception cref="ArgumentException"/>
  193. /// <exception cref="ArgumentNullException"/>
  194. /// <exception cref="DirectoryNotFoundException"/>
  195. /// <exception cref="IOException"/>
  196. /// <exception cref="NotSupportedException"/>
  197. /// <exception cref="UnauthorizedAccessException"/>
  198. /// <exception cref="DirectoryReadOnlyException"/>
  199. /// <param name="transaction">The transaction.</param>
  200. /// <param name="path">The name of the directory to remove.</param>
  201. /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param>
  202. /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only <see cref="FileAttributes"/> of files and directories.</param>
  203. [SecurityCritical]
  204. public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly)
  205. {
  206. DeleteDirectoryCore(null, transaction, path, recursive, ignoreReadOnly, !recursive, false, PathFormat.RelativePath);
  207. }
  208. /// <summary>[AlphaFS] Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
  209. /// <exception cref="ArgumentException"/>
  210. /// <exception cref="ArgumentNullException"/>
  211. /// <exception cref="DirectoryNotFoundException"/>
  212. /// <exception cref="IOException"/>
  213. /// <exception cref="NotSupportedException"/>
  214. /// <exception cref="UnauthorizedAccessException"/>
  215. /// <exception cref="DirectoryReadOnlyException"/>
  216. /// <param name="transaction">The transaction.</param>
  217. /// <param name="path">The name of the directory to remove.</param>
  218. /// <param name="recursive"><see langword="true"/> to remove directories, subdirectories, and files in <paramref name="path"/>. <see langword="false"/> otherwise.</param>
  219. /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only <see cref="FileAttributes"/> of files and directories.</param>
  220. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  221. [SecurityCritical]
  222. public static void DeleteTransacted(KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, PathFormat pathFormat)
  223. {
  224. DeleteDirectoryCore(null, transaction, path, recursive, ignoreReadOnly, !recursive, false, pathFormat);
  225. }
  226. #endregion // Transactional
  227. #region Internal Methods
  228. /// <summary>Deletes the specified directory and, if indicated, any subdirectories in the directory.</summary>
  229. /// <remarks>The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed.</remarks>
  230. /// <exception cref="ArgumentException"/>
  231. /// <exception cref="ArgumentNullException"/>
  232. /// <exception cref="DirectoryNotFoundException"/>
  233. /// <exception cref="IOException"/>
  234. /// <exception cref="NotSupportedException"/>
  235. /// <exception cref="UnauthorizedAccessException"/>
  236. /// <exception cref="DirectoryReadOnlyException"/>
  237. /// <param name="fileSystemEntryInfo">A FileSystemEntryInfo instance. Use either <paramref name="fileSystemEntryInfo"/> or <paramref name="path"/>, not both.</param>
  238. /// <param name="transaction">The transaction.</param>
  239. /// <param name="path">The name of the directory to remove. Use either <paramref name="path"/> or <paramref name="fileSystemEntryInfo"/>, not both.</param>
  240. /// <param name="recursive"><see langword="true"/> to remove all files and subdirectories recursively; <see langword="false"/> otherwise only the top level empty directory.</param>
  241. /// <param name="ignoreReadOnly"><see langword="true"/> overrides read only attribute of files and directories.</param>
  242. /// <param name="requireEmpty"><see langword="true"/> requires the directory must be empty.</param>
  243. /// <param name="continueOnNotExist"><see langword="true"/> does not throw an Exception when the file system object does not exist.</param>
  244. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  245. [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
  246. [SecurityCritical]
  247. internal static void DeleteDirectoryCore(FileSystemEntryInfo fileSystemEntryInfo, KernelTransaction transaction, string path, bool recursive, bool ignoreReadOnly, bool requireEmpty, bool continueOnNotExist, PathFormat pathFormat)
  248. {
  249. #region Setup
  250. if (pathFormat == PathFormat.RelativePath)
  251. Path.CheckSupportedPathFormat(path, true, true);
  252. if (fileSystemEntryInfo == null)
  253. {
  254. // MSDN: .NET 3.5+: DirectoryNotFoundException:
  255. // Path does not exist or could not be found.
  256. // Path refers to a file instead of a directory.
  257. // The specified path is invalid (for example, it is on an unmapped drive).
  258. fileSystemEntryInfo = File.GetFileSystemEntryInfoCore(true, transaction, Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator), continueOnNotExist, pathFormat);
  259. }
  260. if (fileSystemEntryInfo == null)
  261. return;
  262. string pathLp = fileSystemEntryInfo.LongFullPath;
  263. #endregion // Setup
  264. // Do not follow mount points nor symbolic links, but do delete the reparse point itself.
  265. // If directory is reparse point, disable recursion.
  266. if (recursive && fileSystemEntryInfo.IsReparsePoint)
  267. recursive = false;
  268. // Check to see if this is a mount point, and unmount it.
  269. if (fileSystemEntryInfo.IsMountPoint)
  270. {
  271. int lastError = Volume.DeleteVolumeMountPointCore(pathLp, true);
  272. if (lastError != Win32Errors.ERROR_SUCCESS && lastError != Win32Errors.ERROR_PATH_NOT_FOUND)
  273. NativeError.ThrowException(lastError, pathLp);
  274. // Now it is safe to delete the actual directory.
  275. }
  276. if (recursive)
  277. {
  278. // Enumerate all file system objects.
  279. foreach (var fsei in EnumerateFileSystemEntryInfosCore<FileSystemEntryInfo>(transaction, pathLp, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.LongFullPath))
  280. {
  281. if (fsei.IsDirectory)
  282. DeleteDirectoryCore(fsei, transaction, null, true, ignoreReadOnly, requireEmpty, true, PathFormat.LongFullPath);
  283. else
  284. File.DeleteFileCore(transaction, fsei.LongFullPath, ignoreReadOnly, PathFormat.LongFullPath);
  285. }
  286. }
  287. #region Remove
  288. startRemoveDirectory:
  289. if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista
  290. // RemoveDirectory() / RemoveDirectoryTransacted()
  291. // In the ANSI version of this function, the name is limited to MAX_PATH characters.
  292. // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
  293. // 2014-09-09: MSDN confirms LongPath usage.
  294. // RemoveDirectory on a symbolic link will remove the link itself.
  295. ? NativeMethods.RemoveDirectory(pathLp)
  296. : NativeMethods.RemoveDirectoryTransacted(pathLp, transaction.SafeHandle)))
  297. {
  298. int lastError = Marshal.GetLastWin32Error();
  299. switch ((uint) lastError)
  300. {
  301. case Win32Errors.ERROR_DIR_NOT_EMPTY:
  302. if (requireEmpty)
  303. // MSDN: .NET 3.5+: IOException: The directory specified by path is not an empty directory.
  304. throw new DirectoryNotEmptyException(pathLp);
  305. goto startRemoveDirectory;
  306. case Win32Errors.ERROR_DIRECTORY:
  307. // MSDN: .NET 3.5+: DirectoryNotFoundException: Path refers to a file instead of a directory.
  308. if (File.ExistsCore(false, transaction, pathLp, PathFormat.LongFullPath))
  309. throw new DirectoryNotFoundException(string.Format(CultureInfo.CurrentCulture, "({0}) {1}", Win32Errors.ERROR_INVALID_PARAMETER, string.Format(CultureInfo.CurrentCulture, Resources.Target_Directory_Is_A_File, pathLp)));
  310. break;
  311. case Win32Errors.ERROR_PATH_NOT_FOUND:
  312. if (continueOnNotExist)
  313. return;
  314. break;
  315. case Win32Errors.ERROR_SHARING_VIOLATION:
  316. // MSDN: .NET 3.5+: IOException: The directory is being used by another process or there is an open handle on the directory.
  317. NativeError.ThrowException(lastError, pathLp);
  318. break;
  319. case Win32Errors.ERROR_ACCESS_DENIED:
  320. var data = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
  321. int dataInitialised = File.FillAttributeInfoCore(transaction, pathLp, ref data, false, true);
  322. if (data.dwFileAttributes != (FileAttributes) (-1))
  323. {
  324. if ((data.dwFileAttributes & FileAttributes.ReadOnly) != 0)
  325. {
  326. // MSDN: .NET 3.5+: IOException: The directory specified by path is read-only.
  327. if (ignoreReadOnly)
  328. {
  329. // Reset directory attributes.
  330. File.SetAttributesCore(true, transaction, pathLp, FileAttributes.Normal, true, PathFormat.LongFullPath);
  331. goto startRemoveDirectory;
  332. }
  333. // MSDN: .NET 3.5+: IOException: The directory is read-only.
  334. throw new DirectoryReadOnlyException(pathLp);
  335. }
  336. }
  337. if (dataInitialised == Win32Errors.ERROR_SUCCESS)
  338. // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission.
  339. NativeError.ThrowException(lastError, pathLp);
  340. break;
  341. }
  342. // MSDN: .NET 3.5+: IOException:
  343. // A file with the same name and location specified by path exists.
  344. // The directory specified by path is read-only, or recursive is false and path is not an empty directory.
  345. // The directory is the application's current working directory.
  346. // The directory contains a read-only file.
  347. // The directory is being used by another process.
  348. NativeError.ThrowException(lastError, pathLp);
  349. }
  350. #endregion // Remove
  351. }
  352. #endregion // Internal Methods
  353. }
  354. }