0

Windows 7 x64 SP1 .NET Framework 3.5 SP1

簡単なコードを書きましたが、時間の経過とともに機能し、2 回目のパスごとに例外が発生します。... つまり: 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.");

なぜそれが起こるのですか?

4

1 に答える 1

1

There are different possible options, where the Directory.Delete can fail with IOException. According to MSDN

A file with the same name and location specified by path exists.

-or- The directory specified by path is read-only, or recursive is false and path is not an empty directory.

-or- The directory is the application's current working directory.

-or- The directory contains a read-only file.

-or- The directory is being used by another process. There is an open handle on the directory or on one of its files, and the operating system is Windows XP or earlier. This open handle can result from enumerating directories and files. For more information, see How to: Enumerate Directories and Files.

In other words: check for open handlers to that directory, check for hidden files.

于 2012-12-13T08:02:56.777 に答える