How to make a read-only file?

I am using the C # StreamWritier class. Questions:

  • How to make a file read-only so that no one can delete or write it?
  • How to create a hidden file?

I create the file as follows:

  private void button1_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog(); save.FileName = textBox1.Text; save.Filter = "Text File | *.rtf"; if (save.ShowDialog() == DialogResult.OK) { StreamWriter writer = new StreamWriter(save.OpenFile()); writer.WriteLine(textBox2.Text); } writer.Dispose(); writer.Close(); } 
+6
source share
3 answers

Hello, you can try using this method.

1

  public static void SetFileReadAccess(string FileName, bool SetReadOnly) { FileInfo fInfo = new FileInfo(FileName); // Set the IsReadOnly property. fInfo.IsReadOnly = SetReadOnly; } 

2

 File.SetAttributes(yourFilePath, FileAttributes.Hidden); 

......

+8
source

You can set the ReadOnly attribute using File.SetAttributes .

Example:

 File.SetAttributes(textBox1.Text, FileAttributes.ReadOnly); 

Note that this only sets the readonly flag, it does not modify the NTFS access control lists (which means that every qualified user can remove the read-only attribute). Also note that this resets all other attributes of the file, which should not be a problem in your case, since you are creating a new file anyway. If you need to keep existing attributes, first use File.GetAttributes and combine the existing flags with the new one (see the Example in the linked MSDN page).


If you need to protect your file from malicious write attempts, you must understand NTFS security (google for "NTFS security" for a lot of resources). Once you understand this, the following question will tell you how to change them in C #:

+4
source

Use this for a read-only file:

 FileAttributes yourFile = File.GetAttributes(yourFilePath); File.SetAttributes(yourFilePath, FileAttributes.ReadOnly); 

Where "yourFilePath" is the string.

For a hidden file:

 FileAttributes yourFile = File.GetAttributes(yourFilePath); File.SetAttributes(yourFilePath, FileAttributes.Hidden); 

And for a regular file (not only for reading, not hidden):

 FileAttributes yourFile = File.GetAttributes(yourFilePath); File.SetAttributes(yourFilePath, FileAttributes.Normal); 

I know that you did not ask to install a normal file, but I think it is useful to know.

+2
source

Source: https://habr.com/ru/post/921945/


All Articles