Read and write text in text files in C#

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.WriteLine(txtName.Text);
stream_writer.WriteLine(txtStreet.Text);
stream_writer.WriteLine(txtCity.Text);
stream_writer.WriteLine(txtState.Text);
stream_writer.WriteLine(txtZip.Text);
stream_writer.Close(); // Don't forget to close the file!

// Clear the TextBoxes.
txtName.Clear();
txtStreet.Clear();
txtCity.Clear();
txtState.Clear();
txtZip.Clear();
}

Always remember to close the file when you are done writing into it. If you don't, some or all of the data may not get written into the file.

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

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


-->