File Reading Demo

This demo shows how to use the System.IO's File class to open a text file for reading purposes. The below content is read from the file Rand.txt.


Raw File Output
"The only proper purpose of a government is to protect man's rights, which means: to protect him from physical violence... The only proper functions of a government are: the police, to protect you from criminals; the army, to protect you from foreign invaders; and the courts, to protect your property and contracts from breach or fraud by others, and to settle disputes by rational rules, according to objective law." -- Ayn Rand

Nicer Output
"The only proper purpose of a government is to protect man's rights, which means: to protect him from physical violence... The only proper functions of a government are: the police, to protect you from criminals; the army, to protect you from foreign invaders; and the courts, to protect your property and contracts from breach or fraud by others, and to settle disputes by rational rules, according to objective law."
-- Ayn Rand


Source Code
<%@ Import Namespace="System.IO" %>
<script language="vb" runat="server">
  sub Page_Load(sender as Object, e as EventArgs)
    'Open a file for reading
    Dim FILENAME as String = Server.MapPath("Rand.txt")

    'Get a StreamReader class that can be used to read the file
    Dim objStreamReader as StreamReader
    objStreamReader = File.OpenText(FILENAME)

    'Now, read the entire file into a string
    Dim contents as String = objStreamReader.ReadToEnd()

    'Set the text of the file to a Web control
    lblRawOutput.Text = contents
    
    'We may wish to replace carraige returns with <br>s
    lblNicerOutput.Text = contents.Replace(vbCrLf, "<br>")
    
    objStreamReader.Close()
  end sub
</script>

    <b>Raw File Output</b><br />
    <asp:label runat="server" id="lblRawOutput" />
    <p>
    <b>Nicer Output</b><br />
    <asp:label runat="server" id="lblNicerOutput" Font-Name="Verdana" />


[Return to the article]