I have the following code and I am trying to delete a folder it works most of the time but occasionally I get an IOException and visual studio says "access denied" The path exist and the folder says it is empty, and no subfolders but I can not delete it using the following code. Any suggestion why this would work most of the time but not always and how to fix it
if ( Directory.Exist( dir2 + "\\Inv")
{
System.IO.DirectoryInfo dirinv = new System.IO.DirectoryInfo(dir2 + "\\Inv");
setAttributesNormal(dirinv);
try
{
Directory.Delete(dir2 + "\\Inv", true);
}
catch (IOException)
{
Directory.Delete(dir2 + "\\Inv", true);
}
catch (UnauthorizedAccessException)
{
Directory.Delete(dir2 + "\\Inv", true);
}
}
}
private void setAttributesNormal(DirectoryInfo dir)
{
foreach (var subDir in dir.GetDirectories())
setAttributesNormal(subDir);
foreach (var file in dir.GetFiles())
{
file.Attributes = FileAttributes.Normal;
}
}