views:

94

answers:

2

How do you clear the read-only flag on a file in .NET and leave the rest intact?

+2  A: 

I would get the FileInfo instance for the file, and then set the IsReadOnly property to false (as per the documentation here: http://msdn.microsoft.com/en-us/library/system.io.fileinfo.isreadonly.aspx):

new FileInfo("path").IsReadOnly = false;

If you insist on using the static GetAttributes and SetAttributes methods on the File class, you can simply do this:

File.SetAttributes("path", 
    File.GetAttributes("path") & ~FileAttributes.ReadOnly);

The general pattern when you want to clear a flag on a bitmap is to take the value for the flag (in this case, FileAttributes.ReadOnly), invert it (using the ~ operator) and then apply the inverted value to the value that contains the various flags (in this case, File.GetAttributes("path")).

casperOne
@casperOne - Thanks. I ended up going the bitwise route simply because I wasn't aware of the "IsReadOnly" flag.
@roygbiv Not a problem. Glad it helped (and possibly answered your question?)
casperOne
+4  A: 

Can't you just do:

FileInfo f = new FileInfo("yourfile.txt");
f.IsReadOnly = false;

Or am I missing something?

Alconja
@Alconja - Thanks. I missed that in the Intellisense dropdown and went the flags route instead. This is definitely easier though.