How can I programatically remove the readonly attribute from a directory in C#?
Using the -=
assignment operator is dangerous for two reasons:
1) It works ONLY IF the ReadOnly
attribute is set, thus a test is required beforehand.
2) It is performing a subtract operation, which is not is not the best choice when working with binary flags. The subtract operation works if condition 1 (above) is true, but additional subtract operations will ALTER OTHER BITS in the FileAttributes
field!
Use &= ~FileAttributes.ReadOnly;
to remove ReadOnly
flag.
Use |= FileAttributes.ReadOnly;
to apply ReadOnly
flag.
Got it finally. ;)
class Program
{
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("c:\\test");
FileAttributes f = di.Attributes;
Console.WriteLine("Directory c:\\test has attributes:");
DecipherAttributes(f);
}
public static void DecipherAttributes(FileAttributes f)
{
// To set use File.SetAttributes
File.SetAttributes(@"C:\test", FileAttributes.ReadOnly);
if ((f & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
Console.WriteLine("ReadOnly");
// To remove readonly use "-="
f -= FileAttributes.ReadOnly;
if ((f & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
Console.WriteLine("ReadOnly");
else
Console.WriteLine("Not ReadOnly");
}
}