ASP.NET: Read and display a text file
From Wiki
Summary: An example of how we can read a text file and bind it's contents to a GridView control
There may be occasions when we would like to display the contents of a flat file (such as a text file). To do so, we can make use of the System.IO.StreamReader object.
First, let's create a simple text file (in this case I've named it TextFile.txt):
- This is line 1
- This is line 2
- This is line 3
- This is line 4
- This is line 5
Then, we'll create a page with just a GridView on it that we'll use to display the contents of this file:
- <%@ Page Language="VB" AutoEventWireup="false" CodeFile="DisplayTextFile.aspx.vb" Inherits="DisplayTextFile" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>Untitled Page</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="GridView1" runat="server">
- </asp:GridView>
- </div>
- </form>
- </body>
- </html>
Next, we need to create an instance of the StreamReader object and point it at the text file. You'll notice that I've used the Server.MapPath method to get a full path to my text file and I've used this method as I placed the file in the root directory of my application, so if you haven't done the same, you'll have to amend the path. We then need to loop through the file using the Peek method and add each line to an object that can be bound to the GridView (in this case I've used an ArrayList). We can then bind this ArrayList directly to the GridView:
- Imports System.IO
- Partial Class DisplayTextFile
- Inherits System.Web.UI.Page
- Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
- ' Declarations
- Dim objStreamReader As New StreamReader(Server.MapPath("TextFile.txt"))
- Dim arrText As New ArrayList
- ' Loop through the file and add each line to the ArrayList
- Do While objStreamReader.Peek() >= 0
- arrText.Add(objStreamReader.ReadLine)
- Loop
- ' Close the reader
- objStreamReader.Close()
- ' Bind the results to the GridView
- GridView1.DataSource = arrText
- GridView1.DataBind()
- End Sub
- End Class
This shows the method in the simplest form I could think of, so feel free to improve on this and apply whatever formatting necessary to show the file contents in a well presented manner.
This Hack is part of the ASP.NET Hacks collection


