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

watch_later Sunday, May 5, 2019
comment 2 Comments

Introduction


This article gives an explanation about how to read and write a text file in asp.net using c# and also explains StreamReader and StreamWriter class. In this article, you will also learn how to read text file into a string as well as how to read text file into a string array and read 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 which is designed for reading a line of information from a text file and it is inherited from the abstract base class TextReader and 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 which 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 text file path from the user as an input, a read-only multiline textbox for show data of the text file and one simple button and on the click event of button we will read text file and display result in read-only multiline textbox. Here I have used bootstrap to create clean an 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 into a string and finally closes the file, here result we put directly to our multiline read-only textbox txtText.

Method 2: Read text file into the string using streamreader
//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 streamreader and using this class we have read the text file but if you observe then we have also used "using" statement that ensures that the method StreamReader.Dis­pose is called. streamreader will open a text file based on the given file path and reads all the text from the file and put into a string and at last, closes the file similarly method 1.


Method 3: Read 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 open file, read text and store into a string array and finally close the file.

Method 4: Read text file into a string array using streamreader 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 "using" statement to ensures that the method StreamReader.Dis­pose is called. In this method, we have used ReadLine() method from StreamReader class and store the result in the string array and based on 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.ReadLines() method is used lines from 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 store result in the string array and then use this array as per method 4 for the further process here you can process your file immediately.

Method 6: Read text file line by line using streamreader 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 ReadLine() method of StreamReader class and this method open a text file, process your data line by line and finally close 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 user interface as I have shown below. Here I have used one multi-line textbox for write 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 a code to write a text file in c# and you have to write 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 have checked the directory for the file is available or not if it is not available then I have created a directory for the file and then process 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 have used "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 example.

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.

avatar
Anonymous

If you need PDF generation functionality for your .net application, ZetPDF is a .net SDK for adding PDF render and print support in .net applications. It is designed to solve most developer’s needs with regards to PDF rendering. Get in touch today so that we can help you.

delete June 27, 2019 at 3:37 AM
avatar

Wow, your post is very helpful. I have learned a lot from your post. Check out this link to learn more and learn about this topic: https://sisayed360.blogspot.com/

delete February 11, 2020 at 5:22 AM



sentiment_satisfied Emoticon