How to read and write to text file in C#
By FoxLearn 12/1/2024 8:02:55 AM 10.62K
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 Print Text in a Windows Form Application Using C#
- How to fill ComboBox and DataGridView automatically in C#
- How to Read text file and Sort list in C#
- How to pass ListView row data into another Form in C#
- How to make a Countdown Timer in C#
- How to Display selected Row from DataGridView to TextBox in C#
- How to Get all Forms and Open Form with Form Name in C#
- How to Get Checked Items In a CheckedListBox in C#