Unfortunately the following code will fail if the file in question is ReadOnly:

File.Delete(path);

So I'd always recommend using the following (especially when Visual Studio keeps annoying checking in files that it shouldn't concern itself with!!)

//Check the file actually exists
if (File.Exists(path))
{
   //If its readonly set it back to normal
//Need to "AND" it as it can also be archive, hidden etc if ( (File.GetAttributes(path) & FileAttributes.ReadOnly)
== FileAttributes.ReadOnly) File.SetAttributes(path, FileAttributes.Normal); //Delete the file File.Delete(path); }

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Thursday, January 24, 2008 2:02 PM | in C# .NET

Comments

Gravatar
# re: C#: Deleting a ReadOnly file
Posted by d
on 2/29/2008 9:42 PM
Might want to try:

if ((File.GetAttributes(path) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)

Since a file attributes can be read only, archive, etc., you would want to "and" it and see if that file contain a ReadOnly attribute.
Gravatar
# re: C#: Deleting a ReadOnly file
Posted by vishav
on 6/17/2008 7:06 PM
hi,
I m thanful for this code.It helps me as i was stuck in same problem.....
Gravatar
# C#: Deleting a ReadOnly file
on 7/6/2008 9:20 AM
use this code if the access to a file is denied in delete or other process
Gravatar
# re: C#: Deleting a ReadOnly file
on 7/6/2008 9:22 AM
use this code for access denied error
Gravatar
# re: C#: Deleting a ReadOnly file
Posted by ukdev
on 9/26/2008 4:39 PM
Nice tip, thanks.
Gravatar
# re: C#: Deleting a ReadOnly file
Posted by Joe
on 11/6/2008 7:31 AM
Thanks buddy that helped an installation issue
Gravatar
# re: C#: Deleting a ReadOnly file
Posted by Imran Akram
on 1/15/2009 1:50 PM
hi Brad,
its a nice tip really

thanks but dont you think we can use
if ( File.GetAttributes(path)
== FileAttributes.ReadOnly)

instead of that &
Gravatar
# re: C#: Deleting a ReadOnly file
Posted by VB.NET FISHING
on 4/4/2009 7:56 PM
Okay so how do you do that for VB 2008, Vista OS (namely NTFS)? Its been 2 days I've been trying to change READ ONLY attrib...all suggestions have failed. [ vb.developing@gmail.com ] if reply with answer here...please also email answer

PS: we're trying to change and del a file with the '{}' in its name.

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 1 and 4 and type the answer here: