Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

Reading and Writing Text Files in ASP.NET

Author: Rachel Nicole

StreamReader and StreamWriter classes are used for reading and writing files in ASP.NET. We will see how to read from and write into a text file in this article.

 

ASP.NET provides nice functionality to write into a file and read from that file by using StreamWriter and StreamReader classes respectively. File and FileInfo classes provide methods to open, create, append copy, move and delete files. The difference in “File” and “FileInfo” classes that File class provides static methods so we don’t need to create instances of the “File” class to call methods. We will use “File” class methods to create StreamWriter and StreamReader for this article.

  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual Basic or Visual C#  > ASP.NET Empty Web Site
  4. Right click on web site > Add New Item > Web Form
  5. Right click on website > Add New Item >  Text File (Make sure name of the file is “TextFile.txt”)
  6. Write code below in Default.aspx page

    <asp:Label ID="Label1" runat="server" Text="Write Something:" ></asp:Label>
       
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       
    <br />
       
    <asp:Button ID="Button1" runat="server" Text="Write in and read from Text File"
       
    onclick="Button1_Click" Width="232px" />
       
    <br />
       
    <asp:Label ID="Label2" runat="server"></asp:Label>

     
  7. Now write code below in Button click event in code behind file. You must have to import or use “System.IO” namespace as you are going to work with files.

    C#
     
    using System.IO;
     
    protected void Button1_Click(object sender, EventArgs e) {
            try {
                string filePath = Server.MapPath("TextFile.txt");
                string writeText = TextBox1.Text;
                StreamWriter sw = File.AppendText(filePath);
                sw.WriteLine(writeText);
                sw.Close();
            }
            catch (Exception ex) {
                Label2.Text = ex.Message;
            }
            try {
                string filePath = Server.MapPath("TextFile.txt");
                StreamReader sr = File.OpenText(filePath);
                string readText = sr.ReadToEnd();
                Label2.Text = readText;
                sr.Close();
            }
            catch (Exception ex) {
                Label2.Text = ex.Message;
            }
        }
     
    VB.NET

    Imports System.IO
     
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
            Try
                Dim filePath As String = Server.MapPath("TextFile.txt")
                Dim writeText As String = TextBox1.Text
                Dim sw As StreamWriter = File.AppendText(filePath)
                sw.WriteLine(writeText)
                sw.Close()
            Catch ex As Exception
                Label2.Text = ex.Message
            End Try
            Try
                Dim filePath As String = Server.MapPath("TextFile.txt")
                Dim sr As StreamReader = File.OpenText(filePath)
                Dim readText As String = sr.ReadToEnd()
                Label2.Text = readText
                sr.Close()
            Catch ex As Exception
                Label2.Text = ex.Message
            End Try
        End Sub

    At first line of the above code snippet, I have created path of the text file. “File” class provides static methods to open, create, delete and copy files. It also provides help to create FileStream objects. AppendText() method takes a path of the file as string argument and creates a StreamWriter that appends text to the existing file. WriteLine() method of StreamWriter object has 17 overloaded versions. One of its overloaded versions takes a string value as argument and write into file with a line break. Write() method of StreamWriter object does not add a line break. 
     
    Path of the file for reading the file is created in the same way as for writing. OpenText() method of the “File” class takes file path as string argument and opens the file for reading. There are other methods to open a file like Open() and OpenRead(). ReadToEnd() method of the StreamReader object reads the stream from current position to the end of the file. ReadLine() reads a single line from the file.
     
    At the end, don’t forget to close StreamWriter or StreamReader object because if you don’t close it, it will not give permission to other users for reading from and writing into this file.
     
  8. Build website and view in browser. Provide any text in TextBox and click on Button to see result on Label.

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to loop through folder to delete files and subfolders in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net