Read and Write Text Files in C# (ASP.NET Web Forms)

Example scope: this guide reads and writes text files with C# in classic ASP.NET Web Forms on .NET Framework. The examples use ASPX pages and server controls. The file and stream concepts also apply elsewhere, but the page code is not an ASP.NET Core example.

This article gives an explanation of how to read and write a text file in asp.net using c# and also explains StreamReader and StreamWriter classes. In this article, you will also learn how to read a text file into a string and how to read a text file into a string array and read a text file line by line.

Requirement:


1) What is a File?
2) What is the StreamReader class?
3) What is the StreamWriter class?
4) Types of ways to read the text file.
5) Read and write a text file with a simple example.

What is a File?

A file is a container in a computer system for storing data on a disk with a name and often a directory path.

What is the StreamReader class?


StreamReader is a class file that is designed for reading a line of information from a text file it is inherited from the abstract base class TextReader this base class represents a reader, which can read a sequential series of characters.

What is the StreamWriter class?


The StreamWriter class is used to write data or information to the text file. It is a class file that is inherited from the abstract class TextWriter which can write a sequential series of characters.

Demonstration


So, as per the given requirement lets, we create a simple example for better understanding. Here we will see the different kinds of ways one by one to read a text file in c#.

So, first, you have to design a user interface with one textbox for getting a .txt filename such as notes.txt from the user as input, a read-only multiline textbox for show data of the text file, and one simple button and on the click event of the button, we will read a text file and display result in the read-only multiline textbox. Here I have used bootstrap to create a clean and creative user interface you can also use your own CSS as per your requirements. 

HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadFile.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Read Text File in C#</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
 
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div class="container mt-3 ">
                <h1>Read Text Files In ASP.NET using C# </h1>
                <br />
                <asp:TextBox ID="txtFilepath" class="form-control" runat="server"></asp:TextBox>
                <div>
                </div>
                <br />
                <div class="form-group">
                    <label for="comment"><b>File Content:</b></label>
                    <textarea id="txtText" runat="server" class="form-control" style="background-color: white;" rows="8" readonly="true"></textarea>
                </div>
                <div class="mt-3">
                    <asp:Button ID="btnRead" runat="server" class="btn btn-primary" Text="Read File" OnClick="btnRead_Click" />
                </div>
            </div>
        </div>
    </form>
</body>
</html>
Now, let's start to write c# code for the read text file and for that you have to write the following code as shown below. 

Read a Text file in C#


Use the following namespaces and complete read-page code-behind.

ReadFile.aspx.cs

The six read methods below are alternatives, not statements to paste together. This is ASP.NET Web Forms on .NET Framework, not ASP.NET Core. Add the following complete code-behind as ReadFile.aspx.cs; its class name matches the page directive. Enter a filename such as notes.txt. Both pages use the application-owned App_Data/TextFiles folder. Save a file with WriteFile.aspx before reading it. Use one read alternative inside the try block of the handler, replacing the default File.ReadAllText statement, where filepath is already defined. Keep the imports shown below.

Methods 1 and 2 preserve the original text and line separators. The line-based methods rebuild the text, so line endings or a final newline can differ. Although reading lines can avoid loading an array, this demo still accumulates all output in a text control; it is not a memory-bounded large-file viewer. The screenshots show the original demonstration; the revised example accepts a filename within App_Data/TextFiles.

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    protected void btnRead_Click(object sender, EventArgs e)
    {
        try
        {
            string fileName = txtFilepath.Text.Trim();
            if (string.IsNullOrEmpty(fileName) || Path.IsPathRooted(fileName) ||
                fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 ||
                Path.GetFileName(fileName) != fileName ||
                !string.Equals(Path.GetExtension(fileName), ".txt", StringComparison.OrdinalIgnoreCase))
            {
                txtText.InnerText = "Enter a plain .txt filename, for example notes.txt.";
                return;
            }
            string filepath = Path.Combine(Server.MapPath("~/App_Data/TextFiles"), fileName);
            txtText.InnerText = string.Empty;
            // Method 1 is the default. Use one alternative below at a time.
            txtText.InnerText = File.ReadAllText(filepath, Encoding.UTF8);
        }
        catch (IOException)
        {
            txtText.InnerText = "The file could not be read. Save it first and check server access.";
        }
        catch (UnauthorizedAccessException)
        {
            txtText.InnerText = "The application cannot read this text file.";
        }
        catch (ArgumentException)
        {
            txtText.InnerText = "Enter a valid .txt filename.";
        }
    }
}

C#


Method 1: Read the text file into the string using File.ReadAllText().
//Method 1: Read Text File into String using File.ReadAllText
 
txtText.InnerText = File.ReadAllText(filepath, Encoding.UTF8);
Explanation of Method 1

As you can see in this example we have used static class File and used File.ReadAllText method. basically, this method opens a text file based on the given file path and reads all the text from the file and put it into a string, and finally closes the file, here results in we put it directly into our multiline read-only textbox txtText.

Method 2: Read the text file into the string using a stream reader
// Method 2: read all text through StreamReader.
using (var streamReader = new StreamReader(filepath, Encoding.UTF8))
{
    txtText.InnerText = streamReader.ReadToEnd();
}
Explanation of Method 2

Here, we have used stream reader and using this class we have read the text file but if you observe then we have also used a "using" statement that ensures that the method StreamReader.Dis­pose is called. stream reader will open a text file based on the given file path and reads all the text from the file and put it into a string and at last, closes the file similarly to method 1.


Method 3: Read the text file into the string array
// Method 3: read text into a string array.
string[] Mylines = File.ReadAllLines(filepath, Encoding.UTF8);
txtText.InnerText = string.Join(Environment.NewLine, Mylines);
Explanation of Method 3

Again this is a very easy way to use static class File as shown in method 1, here we have used File.ReadAllLines() method and this method opens the file, reads the text and stores it into a string array, and finally closes the file.

Method 4: Read text file into a string array using stream reader class
// Method 4: collect lines, then convert to a string array.
var strlist = new List<string>();
using (var streamReader = new StreamReader(filepath, Encoding.UTF8))
{
    string strline;
    while ((strline = streamReader.ReadLine()) != null)
    {
        strlist.Add(strline);
    }
}
string[] Mylines = strlist.ToArray();
txtText.InnerText = string.Join(Environment.NewLine, Mylines);
Explanation of Method 4

The implementation is similar to method 2 where we have used the "using" statement to ensure that the method StreamReader.Dis­pose is called. In this method, we have used ReadLine() method from StreamReader class and stored the result in the string array and based on the string array showed the result in the text area.

Method 5: Read text file line by Line
//Method 5: Read Text File Line by Line
 
foreach (string strline in File.ReadLines(filepath, Encoding.UTF8))
{
    txtText.InnerText += strline + "\n";
}
Explanation of Method 5

File.ReadLines returns lines as they are read, so a caller can process each line without first creating an array. This display example still accumulates the complete text in the output control, so large files need a different display strategy.

Method 6: Read text file line by line using stream reader class
// Method 6: process each line through StreamReader.
using (var Reader = new StreamReader(filepath, Encoding.UTF8))
{
    string strline;
    while ((strline = Reader.ReadLine()) != null)
    {
        txtText.InnerText += strline + Environment.NewLine;
    }
}
Explanation of Method 6

The explanation for this method is similar to the previous method here we just used the ReadLine() method of StreamReader class and this method opens a text file, processes your data line by line, and finally closes the text file.

Write a Text file in C#


Now, Let's learn how to write a text file in C#, for that you have to design a user interface as I have shown below. Here I have used one multi-line textbox for writing an input text, one text box for a .txt filename, and one simple button for writing a text into a file.

HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WriteFile.aspx.cs" Inherits="WriteFile" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Write Text File in C#</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
 
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div class="container mt-3 ">
                <h1>Write Text Files In ASP.NET using C# </h1>
                <br />
                <div class="form-group">
                    <label for="comment"><b>File Content:</b></label>
                    <textarea id="txtText" runat="server" class="form-control" style="background-color: white;" rows="8"></textarea>
                </div>
                <div>
                    <asp:TextBox ID="txtFilepath" class="form-control" runat="server" placeholder="Text filename, for example notes.txt"></asp:TextBox>
                </div>
                <div class="mt-3">
                    <asp:Button ID="btnWrite" runat="server" class="btn btn-primary" Text="Write File" OnClick="btnWrite_Click" />
                </div>
                <asp:Label ID="lblMessege" runat="server"></asp:Label>
            </div>
        </div>
    </form>
</body>
</html>

C#


Let's start to write code to write a text file in c# and you have to write the following code in the code behind that I showed below.

For WriteFile.aspx.cs, use the complete class below. Create the directory separately from the filename; passing a full filename to Directory.CreateDirectory creates a directory at that name. This demo overwrites an existing text file. Restrict the page to authorized users and grant the application identity only the required access to App_Data/TextFiles. See Directory.CreateDirectory.

using System;
using System.IO;
using System.Text;

public partial class WriteFile : System.Web.UI.Page
{
    protected void btnWrite_Click(object sender, EventArgs e)
    {
        try
        {
            string fileName = txtFilepath.Text.Trim();
            if (string.IsNullOrEmpty(fileName) ||
                Path.IsPathRooted(fileName) ||
                Path.GetFileName(fileName) != fileName ||
                fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 ||
                !string.Equals(Path.GetExtension(fileName), ".txt", StringComparison.OrdinalIgnoreCase))
            {
                lblMessege.Text = "Enter a plain .txt filename, for example notes.txt.";
                return;
            }

            string directory = Server.MapPath("~/App_Data/TextFiles");
            Directory.CreateDirectory(directory);
            string filePath = Path.Combine(directory, fileName);
            using (StreamWriter writer = new StreamWriter(filePath, false, new UTF8Encoding(false)))
            {
                writer.WriteLine(txtText.InnerText);
            }
            lblMessege.Text = "Text file saved.";
        }
        catch (IOException)
        {
            lblMessege.Text = "The file could not be written. Check the filename and server access.";
        }
        catch (UnauthorizedAccessException)
        {
            lblMessege.Text = "The application cannot write to its text-file folder.";
        }
        catch (ArgumentException)
        {
            lblMessege.Text = "Enter a valid .txt filename.";
        }
    }
}

Explanation


The handler validates a plain .txt filename, creates the application-owned directory if necessary, and combines the directory with the filename. It never passes the full filename to Directory.CreateDirectory. Here I have used the WriteLine() method from StreamWriter to write text into a file. The WriteLine() accepts a string as an argument and we have also used the "using" statement so this ensures that the method StreamWriter.Dis­pose is called. 

Output

Read Text Files In ASP.NET using C#
Write Text Files In ASP.NET using C#
Read And Write Text Files In ASP.NET using C#

Summary


In this article, we learned how to read and write a text file in ASP.NET with bootstrap 4 in c#, as well as we also learned what is the StreamReader and StreamWriter class with examples.

About the author

Nikunj Satasiya

Software Engineer

Nikunj Satasiya writes practical tutorials on C#, ASP.NET Core, SQL Server, and Angular at Codingvila. He explains development workflows through focused code examples, clear reasoning, and troubleshooting guidance.

Join the discussion

Ask a question or share an implementation detail. Comments are reviewed before publication.