Troubleshooting Recursive Directory Deletion in .NET 3.5
The common error "System.IO.IOException: The directory is not empty" when using Directory.Delete(path, true)
in .NET 3.5 is misleading. The true
parameter indicates recursive deletion, but it doesn't automatically handle files within the directory.
To reliably delete a directory and its contents recursively, a custom function is necessary:
<code class="language-csharp">public static void DeleteDirectoryRecursively(string targetDir) { string[] files = Directory.GetFiles(targetDir); string[] dirs = Directory.GetDirectories(targetDir); foreach (string file in files) { File.SetAttributes(file, FileAttributes.Normal); // Remove read-only attributes File.Delete(file); } foreach (string dir in dirs) { DeleteDirectoryRecursively(dir); // Recursive call for subdirectories } Directory.Delete(targetDir, false); // Delete the directory itself }</code>
This improved method first removes any read-only attributes from files, then deletes each file individually. It recursively calls itself to handle nested subdirectories before finally deleting the target directory. This ensures complete and error-free removal. Implementing access restrictions is recommended to prevent accidental deletion of system-protected folders.
The above is the detailed content of Why Does Directory.Delete(path, true) Fail, and How Can I Recursively Delete a Directory in .NET 3.5?. For more information, please follow other related articles on the PHP Chinese website!