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’ directoryException: 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?
There are different possible options, where the
Directory.Deletecan fail withIOException.According to MSDN
In other words: check for open handlers to that directory, check for hidden files.