C#: Deleting a ReadOnly file

by Brad 24. January 2008 14:02

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

Tags:

C#

Comments

2/29/2008 9:42:32 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.

d |

6/17/2008 6:06:34 PM #

hi,
   I m thanful for this code.It helps me as i was stuck in same problem.....  

vishav |

7/6/2008 8:20:40 AM #

use this code if the access to a file is denied in delete or other process

Mohammed El Banna |

7/6/2008 8:22:51 AM #

use this code for access denied error

Mohammed El Banna |

9/26/2008 3:39:05 PM #

Nice tip, thanks.

ukdev |

11/6/2008 7:31:47 AM #

Thanks buddy that helped an installation issue

Joe |

1/15/2009 1:50:17 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 &

Imran Akram |

4/4/2009 6:56:30 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.

VB.NET FISHING |

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar