How to make a “Read only” file?

寵の児 提交于 2019-11-30 03:14:12

问题


I'm using the C# StreamWritier class. Questions:

  1. How can I make a file read-only, so that no one can delete or write to it?
  2. How can I make a hidden file?

I'm creating the file like so:

    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();
    }

回答1:


Hello you can try with 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);

......




回答2:


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 (meaning that every skilled user can remove the read-only attribute). Note also that this resets all other attributes of the file, which should not be a problem in your case, since your are creating a new file anyway. If you need to keep existing attributes, use File.GetAttributes first and combine the existing flags with your new one (see the example on the linked MSDN page).


If you need to secure the file against malicious write attemts, you must understand NTFS security (google for "NTFS security" for lots of resources). Once you understand that, the following question will tell you how to modify them in C#:

  • Setting NTFS permissions in C#.NET



回答3:


Use this for a Read Only file:

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

Where "yourFilePath" is a string.

For a hidden file:

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

And for a normal file (not Read Only, nor Hidden):

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

I know you didn't ask for setting a normal file but I think it's useful to know this.




回答4:


Same answer, but with one line of code:

// Hide and read-only in one line
File.SetAttributes(filePathFinal, FileAttributes.ReadOnly | FileAttributes.Hidden);


来源:https://stackoverflow.com/questions/11777924/how-to-make-a-read-only-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!