Read and write text in text files in C#

[text files]

When you click the example program’s Write button, the following code writes the values in the text boxes into a file.

// Write the text values into the file.
private void btnWrite_Click(object sender, EventArgs e)
    StreamWriter stream_writer = new StreamWriter(txtFile.Text);
    stream_writer.Close();  // Don't forget to close the file!

    // Clear the TextBoxes.

This code creates a new StreamWriter to write into a file. It then uses the writer’s WriteLine method to write text into the file. The code finishes by closing the file and blanking the textboxes.

Always remember to close the file when you are done writing into it. The StreamWriter buffers data in memory and only actually writes it into the file when the buffer is full. If you don’t close the file, some or all of the data may not get written onto the disk.

When you click the example program’s Read button, the following code reads the values from the file back into the text boxes.

// Read the values back into the TextBoxes.
private void btnRead_Click(object sender, EventArgs e)
    StreamReader stream_reader = new StreamReader(txtFile.Text);

    txtName.Text = stream_reader.ReadLine();
    txtStreet.Text = stream_reader.ReadLine();
    txtCity.Text = stream_reader.ReadLine();
    txtState.Text = stream_reader.ReadLine();
    txtZip.Text = stream_reader.ReadLine();

This code open the file for reading by creating a new StreamReader associated with it. It then uses that object’s ReadLine method to read the lines form the file and display them in the text boxes.

The StreamWriter and StreamReader classes are designed to write and read strings in text files, and they make that fairly easy. Your code can then do things like parse the text to get numeric values if needed.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in files and tagged , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Read and write text in text files in C#

  1. Eddie Bole says:

    Hi Steven.
    Just wondering how to save the text file to the current path so that all that you type into the text filename field is data.txt (I know in Vb6 to save to the current path it was App.path). Also how do you append the text instead of writing to a new line each time. Sorry for the basic questions, but I’m learning from a Vb6 background. Regards Eddie

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.