Click here to Skip to main content
Click here to Skip to main content

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

, 7 Jan 2011
Rate this:
Please Sign up or sign in to vote.
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.

License

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

About the Author

Anupama Roy
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 Pinmemberlinuxjr11-Jan-11 8:46 
GeneralReason for my vote of 5 Nice share! PinmvpSandeep Mewara8-Jan-11 7:03 
GeneralHave a look at this link: http://www.codeproject.com/script/... PinmvpSandeep Mewara5-Jan-11 8:35 
GeneralThank you Sandeep for your valuable comments.I need some hel... PinmemberAnupama Roy5-Jan-11 6:28 
GeneralI have updated your Tip/Trick based on what you were trying ... PinmvpSandeep Mewara5-Jan-11 5:18 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 7 Jan 2011
Article Copyright 2011 by Anupama Roy
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid