Hi, why i can read and write to file?
Show error only on the "file". Any other well, but I can not read or write.

I use: using System.IO;

private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.ShowDialog();
            textBox1.Text = of.FileName;

            file = new FileStream(textBox1.Text, FileMode.OpenOrCreate, FileAccess.Read);

            StreamReader sr = new StreamReader(file);

            string s = sr.ReadToEnd();

            sr.Close();

            file.Close();
                       
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog of = new SaveFileDialog();
            of.ShowDialog();
            textBox2.Text = of.FileName;

            MessageBox.Show(textBox2.Text);

            FileStream file = new FileStream(textBox2.Text, FileMode.OpenOrCreate, FileAccess.Write);

            StreamWriter sw = new StreamWriter(file);

            sw.Write("Hello file system world!");

            sw.Close();

            file.Close();
      
        }

So, on your READ, you want to create an empty file if one does not exist?

Also, if you put a try/catch block around it, the problem could be revealed.

Also, StreamReader and StreamWriter will take a filename as a parameter, so you can avoid the extra step of the "File" creation.

Edited 7 Years Ago by thines01: typo

when I write want to create a new file.
But why not work now writing the file did not understand

>>StreamWriter sw = new StreamWriter(file);
IMO a StreamWriter expects a filename as of.FileName, not a FileStream like file.

The technique you use for the write WILL work. Maybe it was the way the input string was formatted from the Dialog Box (?)

Here's the test I did:

public static void doWrite()
      {
         FileStream file = new FileStream(@"c:\science\doWrite.txt", FileMode.OpenOrCreate, FileAccess.Write);
         StreamWriter sw = new StreamWriter(file);
         sw.Write("Hello file system world!");
         sw.Close();
         file.Close();
      }

Here's that same test without the "FileStream"

public static void doWrite2()
      {
         StreamWriter sw = new StreamWriter(@"c:\science\doWrite.txt");
         sw.Write("Hello file system world!");
         sw.Close();
      }

Both work.

This article has been dead for over six months. Start a new discussion instead.