Click here to Skip to main content
15,891,423 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
7 Jan 2011CPOL 32.6K   6   5
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.
C#
//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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Dell
India India
I am a .Net developer working on C#,Asp.net,WCF,WF etc.I would like to utilize this space to share whatever I have come across so far working in .Net so that you can also learn & explore.

I hope you find these posts useful.I’d love to hear from you,so please post in your comments/feedback.

Visit my blog http://dotnetforyou.wordpress.com/ for more technical articles:

Comments and Discussions

 
GeneralReason for my vote of 5 Thanks for sharing Pin
linuxjr11-Jan-11 8:46
professionallinuxjr11-Jan-11 8:46 
GeneralReason for my vote of 5 Nice share! Pin
Sandeep Mewara8-Jan-11 7:03
mveSandeep Mewara8-Jan-11 7:03 
GeneralHave a look at this link: http://www.codeproject.com/script/... Pin
Sandeep Mewara5-Jan-11 8:35
mveSandeep Mewara5-Jan-11 8:35 
GeneralThank you Sandeep for your valuable comments.I need some hel... Pin
Anupama Roy5-Jan-11 6:28
Anupama Roy5-Jan-11 6:28 
GeneralI have updated your Tip/Trick based on what you were trying ... Pin
Sandeep Mewara5-Jan-11 5:18
mveSandeep Mewara5-Jan-11 5:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.