Parag’s Den

Dedicated to my adored friends…..

How to Read a text file in ASP .NET?

Posted by paragdongre on November 6, 2007


Introduction

This article is a continuation of the article, Creating Text Files in ASP .NET. In this article, we will see read the text file which we created earlier.

Things that we will be learning in this article
  1. The namespace that is required to deal with Files
  2. The StreamReader Object
  3. Reading a Text File
  4. How to capture errors which may occur while reading a text file?
The Namespace that is required to deal with Files

We require the namespace, System.IO to work with files. So, we should import this namespace in our ASPX page such as<%@ Import Namespace=”System.IO” %>

How to Read a text File?

To start with, we need to create an instance of the object, StreamReader. The instance will be the file pointer for us. Once we have a File Pointer, we need to invoke the method, OpenText method of the object, File. The method, OpenText takes a string as an argument. The string is nothing but the path of file that is going to get created. Now, let us see an example. Let us assume, we have a textbox with textmode set to MultiLine and a button. On the click event of the button, we need to read the text file. The code within the Click event is shown below.

Code in the OnClick event of button.
    Sub WriteToFile(sender As Object, e As EventArgs)        Dim fp As StreamReader

        Try
            fp = File.OpenText(Server.MapPath(“.\Upload\”) & “test.txt”)
            txtMyFile.Text = fp.ReadToEnd()
            lblStatus.Text = “File Succesfully Read!”
            fp.Close()
        Catch err As Exception
            lblStatus.Text = “File Read Failed. Reason is as follows

” & err.ToString()
        Finally

        End Try

    End Sub

How it works?

We are first creating an instance of StreamReader, which is termed as fp (file pointer). Then, in the Try block, we invoke the OpenText method. To read the content, we use the method, ReadToEnd. Actually, we have just three lines of code which reads content from a text file. Once we have read the content from the text file, we close the StreamReader by invoking the Close method of StreamReader.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: