It took sometime to figure out what went wrong when I was getting an Unauthorized Access Exception when trying to delete folder from C#.
There was a misleading factor that the folder was residing on our server & had an impression that authorization is not given to do so.I started thinking from a code perspective,when I could delete the folder manually & later via code when I manually changed the readonly attribute to false. So the problem was that readonly attribute gets set by itself while folder/file is getting created or copied via code hence it will not let you delete unless you remove the attributes.
I am adding the code snippet to delete the folder with the comments herewith
public void RemoveFolder(string[] FolderNames)
{
//Gets Path from web.config
string Path = ConfigurationManager.AppSettings[“Root”];
//Loops through all the folder names & form the DirectoryInfo Path
FolderNames.ToList().ForEach(foldername =>
{
DirectoryInfo Folder = new DirectoryInfo(Path + @”\” + foldername.Trim());
//Checks if folder exists in the Path provided
if (Folder.Exists)
{
//Sets attributes for the DirectoryInfo
Folder.Attributes = Folder.Attributes & ~System.IO.FileAttributes.ReadOnly;
//Gets all files inside the folder
FileInfo[] files = Folder.GetFiles();
//For each file,set the attributes so that it does not throw
//unauthorized access exception while trying to delete
Array.ForEach<FileInfo>(files, new Action<FileInfo>(
f =>
{
File.SetAttributes(f.FullName, FileAttributes.Normal);
}));
Folder.Delete(true);
}
});
}
Hope you find this post useful 🙂