Date:

Share:

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

Related Articles

This article explains how to read and write a text file in asp.net using c# and also explains the 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.

demand:

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 on a computer system for storing data on disk with a name and often a directory path.

What is the StreamReader class?

StreamReader is a class file that is designed to read a line of information from a text file that inherits from the abstract base class TextReader This base class represents a reader, which can read a continuous series of characters.

What is the StreamWriter class?

The StreamWriter class is used to write data or information to the text file. This is a class file that inherits from the TextWriter abstract class that can write a continuous series of characters.

demonstration

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

So, first, you need to design a UI with one text box to receive the text file path from the user as input, a read-only multi-line text box to display the text file data, and one simple button and on the click event of the button, we’ll call a text file and display the result in the read-only multi-line text box . Here I have used bootstrap to create a clean and creative UI, 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 writing c# code for the read text file and for that you need to write the following code as shown below.

Read a text file in C#

Before starting to write code, 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 used a static class file and in use 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 puts it into a string, and finally closes the file, and here we put it directly into our read-only box 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 used a stream reader And using this class we read the text file but if you observe then we also used “Through” A statement promising that the method StreamReader. Dispose Called. The stream reader will open a text file based on the given file path and read all the text from the file and put it into a string and finally close the file similar 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 a static class file as shown in method 1, here we used File.ReadAllLines() method and this method opens the file, reads the text and stores it in a string array, and finally closes the file.

Method 4: Read a text file into an array of strings using the 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 application is similar to method 2 that we used in “Through” A statement to ensure that the method StreamReader. Dispose Called. This method, we used line read() A method from the StreamReader class and store the result in the array of strings and based on the array of strings show the result in the text area.

Method 5: Read a 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 we again used the static class File that we used File.Readline() The method is used on lines from a text file one by one And while you have a very large text file Improving Performance For reading a file you can use this method here instead of storing the result in the string array and then use this array as per method 4 to continue the process where you can process your file immediately.

Method 6: Read a text file line by line using class reader stream

//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 only we used line read() method of StreamReader This class and method opened text file, processes Your data row by row, and finally closed down the text file.

Write a text file in C#

Now, let’s learn how to write a text file in C#, for this you need to design a user interface as I have shown below. Here I have used one multi-line text box to write input text, one text box for file path, and one simple button to write text to 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 writing a code to write a text file in c# and you need to write the following code in the code behind which I have shown 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 previous code I checked that the directory of the file is available or not if it is not available then I created a directory for the file and then processed it further. Here I used WriteLine() A method from StreamWriter to write text to a file. The WriteLine() takes a string as an argument and we’ve also used a “using” statement so this ensures that the method StreamWriter. Dispose Called.

Productivity

Write text files in ASP.NET using C#
Reading and writing 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#, we also learned what StreamReader and StreamWriter class are with examples.

Source

Popular Articles