How to Read and Write Text File in Asp.Net C#, VB

Introduction: In this article I am going to explain the use of StreamReader and StreamWriter Class for reading and writing text file i.e. Notepad file in Asp.Net using both C# and VB Language.

How to Read and Write Text File in Asp.Net C#, VB


Description:  While working on asp.net project it was required to write the contents of one textbox to the text file located in a folder under root of our application and then read the content from that text file and insert in another textbox as shown in image above. Here I have written the simple code to read and write text file.

 Implementation: Let’s create a sample page for demonstration purpose.

HTML Source

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td style="text-align:center">
                        <asp:TextBox ID="txtWriteContent" runat="server" TextMode="MultiLine" Rows="5" Columns="50"></asp:TextBox><br /><asp:Button ID="btnWrite" runat="server" Text="Write To File" OnClick="btnWrite_Click" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align:center">
                         <asp:TextBox ID="txtReadContent" runat="server" TextMode="MultiLine" Rows="5" Columns="50"></asp:TextBox><br /><asp:Button ID="btnRead" runat="server" Text="Read From File" OnClick="btnRead_Click" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Note: Create a folder in Root of your application and Name it "TestFolder". Text file will be created in this folder to write to and read from.

Asp.Net C# Code to write and read text file

using System;

using System.IO;

    protected void btnWrite_Click(object sender, EventArgs e)
    {
        WriteToFile("testFile.txt");
    }
    protected void btnRead_Click(object sender, EventArgs e)
    {
        txtReadContent.Text = ReadFromFile("testFile.txt");
    } 
    private void WriteToFile(String fileName)
    {
        string filePath = Path.Combine(Request.PhysicalApplicationPath, string.Format("{0}\\{1}", "TestFolder", fileName));
        //OR string filePath = Path.Combine(Server.MapPath("~/TestFolder"), fileName);
        using (StreamWriter sw = new StreamWriter(filePath))
        {
            sw.WriteLine(txtWriteContent.Text);
        }
    }
    public string ReadFromFile(String fileName)
    {
        string fileText = string.Empty;
        string filePath = Path.Combine(Request.PhysicalApplicationPath, string.Format("{0}\\{1}", "TestFolder", fileName));
        //OR string filePath = Path.Combine(Server.MapPath("~/TestFolder"), fileName);

        if (File.Exists(filePath))
        {
            using (StreamReader sr = new StreamReader(filePath))
            {
                fileText = sr.ReadToEnd();
            }
        }
        return fileText;
    }

NoteIn the above WriteToFile function the StreamWriter class will create the text file if it does not exist and over write the file if it does exist.

Asp.Net VB Code to write and read text file

Imports System.Data

Imports System.IO

    Protected Sub btnRead_Click(sender As Object, e As EventArgs)
        txtReadContent.Text = ReadFromFile("testFile.txt")
    End Sub
    Protected Sub btnWrite_Click(sender As Object, e As EventArgs)
        WriteToFile("testFile.txt")
    End Sub
    Public Function ReadFromFile(fileName As [String]) As String
        Dim fileText As String = String.Empty
        Dim filePath As String = Path.Combine(Request.PhysicalApplicationPath, String.Format("{0}\{1}", "TestFolder", fileName))
        'OR string filePath = Path.Combine(Server.MapPath("~/TestFolder"), fileName);

        If File.Exists(filePath) Then
            Using sr As New StreamReader(filePath)
                fileText = sr.ReadToEnd()
            End Using
        End If
        Return fileText
    End Function
    Private Sub WriteToFile(fileName As [String])
        Dim filePath As String = Path.Combine(Request.PhysicalApplicationPath, String.Format("{0}\{1}", "TestFolder", fileName))
        'OR string filePath = Path.Combine(Server.MapPath("~/TestFolder"), fileName);
        Using sw As New StreamWriter(filePath)
            sw.WriteLine(txtWriteContent.Text)
        End Using
    End Sub

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.
Previous
Next Post »

1 comments:

Click here for comments
Anonymous
admin
August 01, 2019 ×

jhakaas.....!!!

Congrats bro Anonymous you got PERTAMAX...! hehehehe...
Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..