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

watch_later 2/21/2023
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 the text file path 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-colorwhite;" 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#


Before starting to write a code you have to add the following namespace.

Namespace

using System.IO;

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 Text File into String using StreamReader
 
var Stream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(Stream, 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 File into String Array
 
string[] Mylines = File.ReadAllLines(filepath, Encoding.UTF8);
string str = string.Empty;
if (Mylines.Length > 0)
{
    foreach (var lines in Mylines)
    {
        str += lines.ToString() + "\n";
    }
    txtText.InnerText = str;
}
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: Read Text File into String Array using StreamReader class
 
var strlist = new List<string>();
var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
    string strline;
    while ((strline = streamReader.ReadLine()) != null)
    {
        txtText.InnerText += strline + "\n";
    }
}
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

In this method again we have used static class File where we used File.Readline() method is used lines from a text file one by one and while you have a very large text file to improve performance for reading a file you can use this method here instead of storing the result in the string array and then using this array as per method 4 for the further process where you can process your file immediately.

Method 6: Read text file line by line using stream reader class
//Method 6: Read Text File Line by Line using StreamReader class
 
using (var Reader = new StreamReader(new FileStream(filepath, FileMode.Open, FileAccess.Read), Encoding.UTF8))
{
    string strline;
    while ((strline = Reader.ReadLine()) != null)
    {
        txtText.InnerText += strline + "\n";
    }
}
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 file path, 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-colorwhite;" rows="8"></textarea>
                </div>
                <div>
                    <asp:TextBox ID="txtFilepath" class="form-control" runat="server" placeholder="File path with file name"></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.
protected void btnWrite_Click(object sender, EventArgs e)
{
    try
    {
        if (!Directory.Exists(txtFilepath.Text))
        {
            Directory.CreateDirectory(txtFilepath.Text);
        }
        using (StreamWriter sw = new StreamWriter(txtFilepath.Text, false))
        {
            sw.WriteLine(txtText.InnerText);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Explanation


As you can see in the code first I checked the directory for the file is available or not if it is not available then I created a directory for the file and then process it further. 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.

Tags:
how to read and split text file in c#
read text file in c# line by line
c# read text file to string
c# read text file line by line to array
c# open text file in notepad
c# read file
how to read a text file in c#
how to write a text file in c#
how to read text from a text file in c#
c# read text file line by line
read text file in c# using streamreader
c# read text file line by line to list
create and write text file in c#
c# write text file

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon