Andrey Bushman
Andrey Bushman

Reputation: 12476

The strange error when deleting the directory

Windows 7 x64 SP1 .NET Framework 3.5 SP1

I have wrote simple code, but it works through time, the exception occurs at every second pass. ... I.e.: it works fine for the even starts: 2, 4, 6, 8, e.t.c., but I get exception for odd starts: 1, 3, 5, 7, 9, e.t.c.

// 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.

Output text:

We begin deleting the 'C:\Users\andrey.bushman\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\GPSM\AdminCAD' directory

Exception: The directory is not empty.

But directory is empty (all files already deleted). I open explorer and see it.

Next code works fine always:

// 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.");

Why it is happen?

Upvotes: 0

Views: 980

Answers (1)

Tigran
Tigran

Reputation: 62248

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.

Upvotes: 1

Related Questions