If you are trying to recursively delete directory a and directory a\b is open in Explorer, b will be deleted but you will get the error 'directory is not empty' for a even though it is empty when you go and look. The current directory of any application (including Explorer) retains a handle to the directory. When you call Directory.Delete(true), it deletes from bottom up: b, then a. If b is open in Explorer, Explorer will detect the deletion of b, change directory upwards cd .. and clean up open handles. Since the file system operates asynchronously, the Directory.Delete operation fails due to conflicts with Explorer.
不完整的解决方案
我最初发布了以下解决方案,想法是中断当前线程,让资源管理器有时间释放目录句柄。
// incomplete!
try
{
Directory.Delete(path, true);
}
catch (IOException)
{
Thread.Sleep(0);
Directory.Delete(path, true);
}
但是,只有当打开的目录是您正在删除的目录的直接子目录时,这才有效。如果a\b\c\d在资源管理器中是打开的,并且你在a上使用这个,这个技术在删除d和c后将会失败。
一个更好的解决方案
此方法将处理深层目录结构的删除,即使在资源管理器中打开了一个较低级别的目录。
/// <summary>
/// Depth-first recursive delete, with handling for descendant
/// directories open in Windows Explorer.
/// </summary>
public static void DeleteDirectory(string path)
{
foreach (string directory in Directory.GetDirectories(path))
{
DeleteDirectory(directory);
}
try
{
Directory.Delete(path, true);
}
catch (IOException)
{
Directory.Delete(path, true);
}
catch (UnauthorizedAccessException)
{
Directory.Delete(path, true);
}
}
尽管我们自己要做额外的递归工作,但我们仍然必须处理过程中可能发生的UnauthorizedAccessException。尚不清楚第一次删除尝试是否为第二次成功的删除尝试铺平了道路,或者仅仅是抛出/捕获异常导致的时间延迟,允许文件系统赶上。
通过在try块的开头添加Thread.Sleep(0),可以减少在典型条件下抛出和捕获的异常数量。此外,在系统负载较重的情况下,您可能会同时浏览这两个目录。删除尝试并失败。可以将此解决方案作为更健壮的递归删除的起点。
一般的答案
此解决方案仅处理与Windows资源管理器交互的特性。如果你想要一个坚如磐石的删除操作,有一件事要记住,任何东西(病毒扫描程序,无论什么)都可能在任何时候对你试图删除的东西有一个开放的句柄。所以你得稍后再试。多久之后,以及尝试了多少次,取决于删除对象的重要性。正如MSDN所示,
健壮的文件迭代代码必须考虑到许多复杂性
文件系统的。
这个无辜的声明,只提供了一个到NTFS参考文档的链接,应该会让你汗毛直竖。
(编辑:很多。这个答案原来只有第一个不完全解。)