Reading and Writing Text Files in C#

Amgad | January 24, 2009 | 0 Comments | 1564 Visits

With all the DBMSs out there, text files are still widely used when developing applications. They are small, fast and do not require any library or application to be installed in the client machine. The System.IO.StreamReader and System.IO.StreamWriter are used to read and write text files to disk.

The following code demonstrates reading a file selected using the OpenFileDialog control and saving to a file using the SaveFileDialog control. The code works with the .NET Framework and Mono 2.0 and later.

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
                return;

            System.IO.StreamReader Reader = new
                System.IO.StreamReader(openFileDialog1.FileName);

            //clear the contents of the textbox
            textBox1.Clear();

            //read the whole file in one read and display it in the textbox
            textBox1.Text = Reader.ReadToEnd();

            Reader.Close();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
                return;

            System.IO.StreamWriter Writer =
                new System.IO.StreamWriter(saveFileDialog1.FileName);

            Writer.Write(textBox1.Text);
            Writer.Close();
        }

 

Download Source Code

Related posts:

Filed Under: Mono 2.0, WinForms

Leave a Reply