How to make a "Read only" file?

Viewed 18079

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

Same answer, but with one line of code:

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

One-line answer to question #1 (without changing other file attributes):

new FileInfo(filename).IsReadOnly = true;
Related