Read and write text in text files in C#

// Write the text values into the file.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.
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();
}
// Read the values back into the TextBoxes.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
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();
}
-->
Comments