Windows Forms: Read and Write text file in C#
By FoxLearn 1/5/2020 4:53:09 AM 14.11K
Read and write text file in c# windows application
Dragging TextBox and Button controls from your Visual Studio Toolbox to your form designer, then create a simple user interface allows you to read and write text file in c#.
Right-clicking on your TextBox control, then select Properties. Next, set the Multiline of TextBox control to True.
C# Read text file line by line
Adding a click event handler to the Read button allows you to read a text file in c#.
//how to read a text file in c# windows forms application private void btnRead_Click(object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text files|*.txt" }) { if (ofd.ShowDialog() == DialogResult.OK) { using (StreamReader read = new StreamReader(ofd.FileName)) { while (true) { string line = read.ReadLine(); if (line == null) break; txtText.Text = line; } } } } }
C# Write string to file
Adding a click event handler to the Write button allows you to write data from the TextBox control to text file.
private void btnWrite_Click(object sender, EventArgs e) { using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Text files|*.txt" }) { if (sfd.ShowDialog() == DialogResult.OK) { using (StreamWriter write = new StreamWriter(sfd.FileName, true, Encoding.UTF8)) { write.WriteLine(txtText.Text); } } } }
You can write a text file with Encoding, It's automatically create and write text file in c#.
C# Write to file append
StreamWriter write = new StreamWriter(sfd.FileName, true, Encoding.UTF8);
Through this c# example, I hope so you can use StreamReader and StreamWrite class to read and write text file in c# windows application.