How to Read and Write text file in C#

By FoxLearn 7/18/2024 8:07:24 AM   14.2K
Reading from and writing to text files using StreamWriter and StreamReader in a C# Windows Forms Application is a common task.

How to Read and write text file in c# windows application

Open your Visual Studio, then create a new Windows Forms application project.

Next, Drag and drop the 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#.

c# read write text file

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)
        {
            // Create a new instance of StreamReader
            using (StreamReader read = new StreamReader(ofd.FileName))
            {
                while (true)
                {
                    // Read the text from the file
                    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)
        {
            // Create a new instance of StreamWriter
            using (StreamWriter write = new StreamWriter(sfd.FileName, true, Encoding.UTF8))
            {
                // Write text to the file
                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);

In this example, we have a Windows Forms application with a textbox (txtInput), and two buttons (btnWrite and btnRead). btnWrite is used to write the content of the textbox to a file, and btnRead is used to read the content of the file.

Through this c# example, I hope so you can use StreamReader and StreamWrite class to read and write text file in c# windows application.

Related