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.

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 1 and 5 and type the answer here: