ASPAlliance.com : The #1 Active Server Pages .NET Community The #1 ASP.NET Community
Search   Search

Subscribe   Subscribe

Powered by ORCSWeb Hosting


Site Stats


Powered By ASP.NET
 
Featured Sponsor

Featured Columnist


Featured Book
Microsoft ASP.NET Step by Step
Microsoft ASP.NET Step by Step

Find Prices


New! asp.netPRO

We publish our articles in the standard RSS format.

Powerful .NET Email Component

Code Sharing Software
Click here to return to my article index

Updated: 9/16/2002 - Thanks to Charles C., Paul M., and Joel M. for pointing out the faulty code.

In this article we will look at a technique that allows us to open a text file and stream its contents to the browser. We will also use the Try..Catch style of error handling (Best Practice Alert!). Read about structured error handling here.

Note: This is not the only technique to open a text file and my not be the preferred technique given certain circumstances.

The code below opens a text file (words.txt) and uses the File class to open a stream using the StreamReader class. We use the StreamReader class to loop through each line in the file, appending (Best Practice Alert! Read about string concatenation best practices here.) it to the string variable myOutputString as we go.

<%@ Page Language="VB" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<html>
<script language="VB" runat=server>
Sub Page_Load(source As Object, E As EventArgs)

	Dim FileName As String = Server.MapPath("words.txt")
	Dim FileContents As String
	Dim myStreamReader As StreamReader

	Try
        	myStreamReader = File.OpenText(strFile)
		FileContents = myStreamReader.ReadToEnd()
		Label1.Text = FileContents
	Catch myException As Exception
		If Not myStreamReader Is Nothing Then
			myStreamReader.Close()  
		End If      	
	End Try

End Sub
</script>
</html>
Result:
This is a test file with some some repeated words that the program will insert into an Label Control

 Copyright © 2000-2003 ASPAlliance.com  Page Rendered at 10/7/2008 12:27:56 PM