OP says he has tried the following code to test whether a directory is read-only:
DirectoryInfo di = new DirectoryInfo(@"e:\\test");
if (di.Attributes == FileAttributes.ReadOnly)
{
MessageBox.Show("Read only"); }
else
{
MessageBox.Show("No");
}
This is
almost correct, it just doesn't take into account the fact that the Attributes property is a "flag" enum, meaning that it can be set to any
combination of the available
FileAttributes[
^] values.
In other words, for a folder, the Attributes property will contain at least
FileAttributes.Directory
, along with any other flags that may be set (like the
ReadOnly
flag).
If we're only interested in a
particular flag (in this case, whether it's read-only), we need to do this:
if ((di.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
The rest of the code can stay as-is.
To clear the read-only flag from a folder, you need to unset the ReadOnly flag in the Attributes property:
di.Attributes = (di.Attributes ^ FileAttributes.ReadOnly);
Note that this may fail if you don't have the correct permissions to make changes to this folder, or if it's a system folder (i.e. it has the
FileAttributes.System
flag set).
Hope this helps.