【问题标题】:The strange error when deleting the directory删除目录时的奇怪错误
【发布时间】:2012-12-13 07:52:49
【问题描述】:

Windows 7 x64 SP1 .NET 框架 3.5 SP1

我编写了简单的代码,但它会随着时间的推移而起作用,异常发生在每一秒通过。 ...即:它适用于偶数开始:2、4、6、8 等,但我对奇数开始有例外:1、3、5、7、9 等

// localMenuDirName is 'GPSM\AdminCAD'.
DirectoryInfo menuDir = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.Programs), localMenuDirName));
if (menuDir.Exists) {
    FileInfo[] files = menuDir.GetFiles("*", SearchOption.AllDirectories);
    foreach (FileInfo file in files) {
        file.IsReadOnly = false;
    }
    sb.AppendLine(String.Format("We begin deleting the '{0}' directory", menuDir.FullName));

    Directory.Delete(menuDir.FullName, true); // Get Exception here

    // menuDir.Delete(true); // here I get same exception.

输出文本:

我们开始删除 'C:\Users\andrey.bushman\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\GPSM\AdminCAD' 目录

例外:目录不为空。

但目录是空的(所有文件都已删除)。我打开资源管理器看看。

下一个代码总是可以正常工作:

// localMenuDirName is 'GPSM\AdminCAD'.
DirectoryInfo menuDir = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.Programs), localMenuDirName));
if (menuDir.Exists) {
    FileInfo[] files = menuDir.GetFiles("*", SearchOption.AllDirectories);
    foreach (FileInfo file in files) {
        file.IsReadOnly = false;
    }
    sb.AppendLine(String.Format("We begin deleting the '{0}' directory", menuDir.FullName));

    try {
        Directory.Delete(menuDir.FullName, true); 
    }
    catch {
        // Try again... Now it works without exception!
        Directory.Delete(menuDir.FullName, true);
    }
    sb.AppendLine("Operation was executed successfully.");

为什么会这样?

【问题讨论】:

  • 您是否在要删除的目录中打开了当前目录的命令提示符?
  • 也许您在 Windows 资源管理器中打开了该目录?然后就删不掉了,根据文档:In some cases, if you have the specified directory open in File Explorer, the Delete method may not be able to delete it.msdn.microsoft.com/en-us/library/62t64db3.aspx
  • @leppie 不,我从其他目录运行我的 exe,工作目录也是其他目录。
  • @dognose 不,我在出现异常后打开目录。

标签: c# .net windows exception directory


【解决方案1】:

有不同的可能选项,Directory.Delete 可能会因IOException 而失败。 根据MSDN

存在路径指定的同名和位置的文件。

-或- path指定的目录是只读的,或者recursive为false且path不是空目录。

-或- 该目录是应用程序的当前工作目录。

-或- 该目录包含一个只读文件。

-或- 目录正被另一个进程使用。目录或其文件之一上有一个打开的句柄,并且操作系统是 Windows XP 或更早版本。此打开句柄可能来自枚举目录和文件。有关详细信息,请参阅如何:枚举目录和文件。

换句话说:检查该目录的打开处理程序,检查隐藏文件。

【讨论】:

  • 不,目录不包含隐藏文件(我创建了这个目录,我检查了它)。但是为什么我的第二个代码工作正常???
  • @Bush:对主题没有明确的想法。只有一个嫌疑人。在您的 first 代码中尝试,在 Directory.Delete 之前注入延迟。假设 Thread.Sleep(200)。看看它是否像第二种情况一样工作。
  • 谢谢。它解决了我的问题。现在也可以使用第一个变体(暂停)。但这对我来说很有趣:为什么???
  • @Bush:对此没有a 证明,但根据我的经验,我在迭代目录中的文件和之后遇到了不同的情况 删除目录失败。原因,我怀疑,在迭代之后,IO 上仍然分配了几毫秒的时间,这意味着,很可能,这种行为在不同的机器之间也会有所不同。
  • 关于“当您调用 Directory.Delete 并且以这种方式打开文件时,Directory.Delete 成功删除所有文件但当 Directory.Delete 调用 RemoveDirectory 时出现“目录不为空”异常被抛出,因为有一个文件被标记为删除但实际上并没有被删除。”
猜你喜欢
  • 1970-01-01
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 2019-09-09
  • 2011-08-26
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多