Use StreamReader and StreamWriter in your WinForms apps
Want to let users save their input, or load data from a file into your form? With just a few lines of code, you can store and retrieve text using file streams.
In C#, we use StreamWriter to write to files and StreamReader to read from them โ safely and efficiently.
๐ Required Namespace
At the top of your form:
using System.IO;
๐ Writing to a Text File
โ๏ธ Example: Save Form Data
private void btnSave_Click(object sender, EventArgs e)
{
string name = txtName.Text;
string age = txtAge.Text;
using (StreamWriter writer = new StreamWriter("user_data.txt"))
{
writer.WriteLine("Name: " + name);
writer.WriteLine("Age: " + age);
}
MessageBox.Show("Data saved to user_data.txt");
}
โ
using block ensures the file is closed properly
โ
Creates the file if it doesn’t exist, overwrites it if it does
๐ Reading from a Text File
๐ Example: Load File into a TextBox
private void btnLoad_Click(object sender, EventArgs e)
{
if (File.Exists("user_data.txt"))
{
using (StreamReader reader = new StreamReader("user_data.txt"))
{
txtOutput.Text = reader.ReadToEnd();
}
}
else
{
MessageBox.Show("File not found.");
}
}
โ
ReadToEnd() grabs the whole file as a string
โ
Also possible: ReadLine() to read line-by-line
โจ Example: Append to a File
Instead of overwriting:
using (StreamWriter writer = new StreamWriter("log.txt", append: true))
{
writer.WriteLine(DateTime.Now + ": User clicked Save");
}
๐ Example Use Case: Save and Load Notes
UI Elements:
TextBox txtNotes(Multiline)Button btnSaveNotesButton btnLoadNotes
Code:
private void btnSaveNotes_Click(object sender, EventArgs e)
{
using (StreamWriter sw = new StreamWriter("notes.txt"))
{
sw.Write(txtNotes.Text);
}
MessageBox.Show("Notes saved!");
}
private void btnLoadNotes_Click(object sender, EventArgs e)
{
if (File.Exists("notes.txt"))
{
using (StreamReader sr = new StreamReader("notes.txt"))
{
txtNotes.Text = sr.ReadToEnd();
}
}
else
{
MessageBox.Show("No notes found.");
}
}
๐งช Quick Challenge
๐งฉ Create a form that:
- Lets users enter Name and Feedback
- Saves the input to a file using
StreamWriter - Loads the content back into a multiline
TextBoxusingStreamReader
๐ Summary
| Class | Use Case |
|---|---|
StreamWriter | Save (write) data to a file |
StreamReader | Load (read) data from a file |
using block | Ensures file is closed safely |
File.Exists() | Check before reading |
โ Best Practices
- โ
Use
usingblocks to manage file streams safely - โ
Check for
File.Exists()before reading - โ
Catch exceptions (
try/catch) for file access errors - โ
Use relative paths for local files (
"data.txt") - โ
Consider file dialogs (
OpenFileDialog,SaveFileDialog) for flexible paths
๐ Want to Go Further?
- Save structured data as CSV or JSON
- Load and parse configuration files on form start
- Use
File.AppendText()for logging - Add save/load confirmation dialogs
๐ฌ Want help wiring up file saving for your forms or reports?
Just share your UI setup โ Iโll help you make it persistent!