How to remove the Read-Only flag on a file in C#

Original post can be found here

Just use the snippet below:

FileInfo myFile = new FileInfo (@"C:\ReadOnlyFile.txt");
if (myFile.IsReadOnly) {
  // remove the Read-Only flag
  myFile.Attributes = (FileAttributes)(Convert.ToInt32(myFile.Attributes) - Convert.ToInt32(FileAttributes.ReadOnly));
}

or, if you want to make it a bit cleaner:

FileInfo myFile = new FileInfo (@"C:\ReadOnlyFile.txt");
if (myFile.IsReadOnly) {
  // remove the Read-Only flag
  myFile.Attributes -= FileAttributes.ReadOnly;
}

Comments