65.9K
CodeProject is changing. Read more.
Home

'Unauthorized Access Exception' when trying to delete folder created from code

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Jan 5, 2011

CPOL
viewsIcon

34084

How to delete a folder created via code programmatically

'Unauthorized Access Exception' when trying to delete folder created from code using C#: If you have created a folder via code, then folder's readonly attributes gets setup. Now in order to delete it from code, one needs to remove the readonly attribute first. If not done,it will throw an Unauthorized Access Exception. If you have a file inside the folder with readonly attribute, then also it will result in same exception.
//Code to remove readonly attributes of folder before delete

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(files, new Action(f =>
                                {
                                  File.SetAttributes(f.FullName, FileAttributes.Normal);
                                }));

Folder.Delete(true);
Hope you find this useful.