How to read and write to text file in C#

By FoxLearn 12/1/2024 8:02:55 AM   10.74K
In C#, reading from and writing to a text file can be done using classes in the System.IO namespace, such as StreamReader, StreamWriter, File, and FileInfo.

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.

c# write text file

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