How to read and write to text file in C#
By FoxLearn 12/1/2024 8:02:55 AM 10.74K
In this article, we will create a Windows Forms application in C# that allows users to read and write text files using OpenFileDialog
and SaveFileDialog
.
How to read and write to text file in C#?
Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "TextFile" and then click OK
Design the form with two buttons (btnRead
and btnWrite
) and a multiline TextBox
(txtText
) for displaying or editing file content as shown below.
Double-click each button in the designer to generate click event handlers.
The functionality is implemented in the btnRead_Click
and btnWrite_Click
event handlers.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TextFile { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // Event handler for the Read button private async void btnRead_Click(object sender, EventArgs e) { // Open a text file and read its content using(OpenFileDialog ofd = new OpenFileDialog() { Filter="Text Documents|*.txt", ValidateNames = true, Multiselect = false }) { if (ofd.ShowDialog() == DialogResult.OK) { using(StreamReader sr = new StreamReader(ofd.FileName)) { txtText.Text = await sr.ReadToEndAsync(); // Asynchronous read } } } } // Event handler for the Write button private async void btnWrite_Click(object sender, EventArgs e) { // Save content to a text file using(SaveFileDialog sfd = new SaveFileDialog() { Filter="Text Documents|*.txt", ValidateNames = true }) { if (sfd.ShowDialog() == DialogResult.OK) { using(StreamWriter sw = new StreamWriter(sfd.FileName)) { await sw.WriteLineAsync(txtText.Text); // Asynchronous write MessageBox.Show("You have been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } } }
Both StreamReader
and StreamWriter
are used with asynchronous methods (ReadToEndAsync
and WriteLineAsync
), ensuring the application remains responsive during file I/O operations.
Build and run the application, then click Read to open and read a text file. Modify the text in the TextBox
and click Write to save the changes to a new file.
VIDEO TUTORIAL
- How to update UI from another thread in C#
- How to get CheckedListBox selected values in C#
- How to use Advanced Filter DataGridView in C#
- How to create a Notification Popup in C#
- How to Use Form Load and Button click Event in C#
- How to Link Chart /Graph with Database in C#
- How to Check SQL Server Connection in C#
- How to Generate Serial Key in C#