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
2009-12-23 21:48:41
@casperOne - Thanks. I ended up going the bitwise route simply because I wasn't aware of the "IsReadOnly" flag.
2009-12-23 22:11:26
@roygbiv Not a problem. Glad it helped (and possibly answered your question?)
casperOne
2009-12-23 22:31:22
+4
A:
Can't you just do:
FileInfo f = new FileInfo("yourfile.txt");
f.IsReadOnly = false;
Or am I missing something?
Alconja
2009-12-23 21:49:13