Read a File and Loop Through Results Using
.NET 2.0
System.IO.Streamreader Class
By Steve Schofield
April 26, 2006
The
System.IO.StreamReader in ASP.NET
2.0 is easy to use when looping through a text file and displaying the contents
to a webpage. This code sample reads a file called niclist.txt and displays the
output to a Label
control. I also created variable ‘x’ that keeps track of how many
lines are in the text file and displays the results to another Label
control.
I use this technique when looping through log files looking for errors. If a certain
error is located, I update the text so it displays different in the browser. This
helps quickly identify the issue.
Example.aspx
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub Page_Load()
Dim reader
As System.IO.StreamReader
Dim sb As
New System.Text.StringBuilder
Dim line As
String = Nothing
Dim x As
Integer = 0
Try
'Open a reader
for the input file, and read line by line
'This shows how-to use Server.MapPath
to map the physical path of the file
reader = New System.IO.StreamReader(Server.MapPath(".") & "/niclist.txt")
sb.Append("<br>")
'Loop through the Stream object
Do
While reader.Peek() >= 0
line = reader.ReadLine()
sb.Append(line &
"<BR>")
x = x + 1
Loop
'Display the number of lines
in the text file to the myLabel1 control
myLabel1.Text = x.ToString()
'Write out the text to the 'myLabel2
control
myLabel2.Text = sb.ToString()
Catch ex As
Exception
Response.Write(ex.ToString())
End Try
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml"
>
<head runat="server">
<title>Read data from a Text file using
System.IO.StreamReader</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Number of lines in my file:
<b><asp:Label ID=myLabel1 runat=server></asp:Label></b>
<br />
<br />
<b>Output from the text file.</b>
<asp:Label ID=myLabel2 runat=server></asp:Label>
</div>
</form>
</body>
</html>
Niclist.txt file
Line 1 Data
Line 2 Data
Line 3 Data
Line 4 Data
Steve Schofield is a Senior Internet Support
Specialist with
ORCS Web, Inc.
- a company that provides managed hosting solutions for clients who develop and deploy their applications on Microsoft Windows platforms. Services include shared hosting, dedicated hosting, and webfarm hosting, with specialty in .Net, SQL Server, and architecting highly scalable solutions.