Click here to Skip to main content
13,558,908 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


6 bookmarked
Posted 5 Jan 2011
Licenced CPOL

'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);


Hope you find this useful.


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#,,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 for more technical articles:

You may also be interested in...


Comments and Discussions

GeneralReason for my vote of 5 Thanks for sharing Pin
linuxjr11-Jan-11 8:46
memberlinuxjr11-Jan-11 8:46 
GeneralReason for my vote of 5 Nice share! Pin
Sandeep Mewara8-Jan-11 7:03
mvpSandeep Mewara8-Jan-11 7:03 
GeneralHave a look at this link: Pin
Sandeep Mewara5-Jan-11 8:35
mvpSandeep Mewara5-Jan-11 8:35 
GeneralThank you Sandeep for your valuable comments.I need some hel... Pin
Anupama Roy5-Jan-11 6:28
memberAnupama Roy5-Jan-11 6:28 
GeneralI have updated your Tip/Trick based on what you were trying ... Pin
Sandeep Mewara5-Jan-11 5:18
mvpSandeep 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180515.1 | Last Updated 7 Jan 2011
Article Copyright 2011 by Anupama Roy
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid