37

I'm trying to set flag that causes the Read Only check box to appear when you right click \ Properties on a file.

Thanks!

Ghasem
  • 14,455
  • 21
  • 138
  • 171
will
  • 3,975
  • 6
  • 33
  • 48
  • Are you trying to make the file read only, per your question, or writeable (not read only), per your question title? – Lasse V. Karlsen Jul 29 '09 at 18:19
  • This is a complicated issue on Win2k based OSes. There's the read-only attribute you can give a file, and there's also Write-permission which is granted via the "Permissions" tab. The former is just a suggestion, where as the latter is actually enforced by the operating system. – Armentage Jul 29 '09 at 18:30
  • @Armentage I don't think it's that complicated. There's a clear distinction between file flags and NTFS permission sets, and this question clearly deals with the first case. – Rex M Jul 30 '09 at 04:46

4 Answers4

69

Two ways:

System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
fileInfo.IsReadOnly = true/false;

or

// Careful! This will clear other file flags e.g. `FileAttributes.Hidden`
File.SetAttributes(filePath, FileAttributes.ReadOnly/FileAttributes.Normal);

The IsReadOnly property on FileInfo essentially does the bit-flipping you would have to do manually in the second method.

Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
Rex M
  • 142,167
  • 33
  • 283
  • 313
37

To set the read-only flag, in effect making the file non-writeable:

File.SetAttributes(filePath,
    File.GetAttributes(filePath) | FileAttributes.ReadOnly);

To remove the read-only flag, in effect making the file writeable:

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

To toggle the read-only flag, making it the opposite of whatever it is right now:

File.SetAttributes(filePath,
    File.GetAttributes(filePath) ^ FileAttributes.ReadOnly);

This is basically bitmasks in effect. You set a specific bit to set the read-only flag, you clear it to remove the flag.

Note that the above code will not change any other properties of the file. In other words, if the file was hidden before you executed the above code, it will stay hidden afterwards as well. If you simply set the file attributes to .Normal or .ReadOnly you might end up losing other flags in the process.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
1

C# :

File.SetAttributes(filePath, FileAttributes.Normal);

File.SetAttributes(filePath, FileAttributes.ReadOnly);
Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
0

One-line answer (without changing other file attributes):

new FileInfo(filename).IsReadOnly = true/false;
Udi Y
  • 258
  • 3
  • 12