Directory.Delete doesn't work. Access denied error but under Windows Explorer it's ok
Thank you all for your input, it helps me in quick find of solution.
As Phil mentioned "Directory.Delete fails if it is, regardless of permissions (see bottom of msdn.microsoft.com/en-us/library/…)"
In addition Unable to remove Read-Only attribute from folder Microsoft says:
You may be unable to remove the Read-Only attribute from a folder using Windows Explorer. In addition, some programs may display error messages when you try to save files to the folder.
Conclusion: always remove all dir,file attributes diffrent then Normal before deleting. So below code solve the problem:
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"E:\3\{90120000-0021-0000-0000-0000000FF1CE}-C1");
if (dir.Exists)
{
setAttributesNormal(dir);
dir.Delete(true);
}
. . .
function setAttributesNormal(DirectoryInfo dir) {
foreach (var subDir in dir.GetDirectories())
setAttributesNormal(subDir);
foreach (var file in dir.GetFiles())
{
file.Attributes = FileAttributes.Normal;
}
}
I used binball's code and added one line to set the directory attributes to normal also.
if (dir.Exists)
{
setAttributesNormal(dir);
dir.Delete(true);
}
function setAttributesNormal(DirectoryInfo dir)
{
foreach (var subDir in dir.GetDirectories())
{
setAttributesNormal(subDir);
subDir.Attributes = FileAttributes.Normal;
}
foreach (var file in dir.GetFiles())
{
file.Attributes = FileAttributes.Normal;
}
}
Based on the directory you are working in, you will probably need administrator access to delete files. To test this, run your app as administrator from explorer and see if it works (right-click the .exe and choose "Run As Administrator").
If that works, you'll need to get administrator privileges when your application executes. You can do this by adding the following to your application manifest:
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator" />
</requestedPrivileges>
</security>
</trustInfo>