Title: Read and write text in text files in C#
Keywords: files, text files, read files, write files, read text files, write text files, StreamReader, StreamWriter, C#, C# programming, example, example program, Windows Forms programming
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 the example to experiment with it and to see additional details.