Codingvila
watch_later 2/21/2023 comment Add CommentThis 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.
A file is a container in a computer system for storing data on a disk with a name and often a directory path.
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.
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.
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.
@ 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.