Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to make a file writeable in c#

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

Thanks!

like image 405
will Avatar asked Jul 29 '09 18:07

will


People also ask

How do you read and write from a file in C?

For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf() . The only difference is that fprintf() and fscanf() expects a pointer to the structure FILE.

How do I format a file in C?

C File Format C files are written in plain text file format following the programming language syntax. A typical C file will have: import statement at the top of the file to import any header Files.


2 Answers

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.

like image 89
Rex M Avatar answered Sep 20 '22 23:09

Rex M


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.

like image 39
Lasse V. Karlsen Avatar answered Sep 23 '22 23:09

Lasse V. Karlsen