Reader Level:
Visual Basic .NET

Application to Read Data from a File using ASP.NET and VB.NET

By Vikram Joshi on Nov 10 2012
I have created a small application by which you can read from a file and display the contents of the file onto the browser.
    • Like
    • Love It
    • Awesome
    • Interesting
    • It's Okay
    • Thumbs Down
  • 6.8k
  • 0

Hello, I have created a small application by which you can read from a file and display the contents of the file onto the browser.

There are ways of reading the opened file like:

  • streamReaderObj.Read()

    Reads the stream character-wise. It returns an integer value equal to the ASCII equivalent of the character read. This is also used in reading the Binary Stream Input. If the end-of-file is reached then it returns  -1.
  • streamReaderObj.ReadLine()

    Reads a line of characters from the current stream and returns the data as a string. if end of stream is reached then it returns Null of "".
  • streamReaderObj.ReadBlock(buffer, index, count)

    Reads data from the stream. The difference in this method is that the readblock method reads data bytes equal the number specified by 'count' into 'buffer' starting from the 'index' position in the 'buffer' .
  • streamReaderObj.ReadToEnd()

    Reads the data from the current stream position to the end of stream.

StreamreaderObj is a StreamReader which reads the Stream which has opened the required text file for reading.

The program that I have made uses the 'read' method for reading the file. Following are the files that have been used:

  1. fileIO.vb    The code behind file.
  2. fileIO.aspx The aspx file which you would call.
  3. blonde.txt The file which will be used to demonstrate the file handling.

In the Zip file I have included all the above files mentioned all you need to do is to copy these files into one web project folder, and give a call to the page.

Be Sure that the aspx files and the blonde.txt are stored in one folder.

Source Code

Protected Sub TxtFileOpen()
Dim str As String
fileObj As File
Dim readChar As Integer = 0
Dim streamReaderObj As StreamReader
Dim streamObj As Stream = fileObj.Open(server.mappath("blonde.txt"), IO.FileMode.Open)
streamReaderObj = New StreamReader(streamObj)
'''when nothing is read then the stream reader read method returns -1
While readChar <> -1
If readChar = 13 Then
'''if the charachter is and enter key (ascii val=13)
str = str + "<BR>"
'''else read line and store it in the string.
''' in this case read returns the ascii integer value of the char read
''' so we need to convert it back to char while printing it on the
str = str + readChar.ToChar
End If
readChar = streamReaderObj.Read
End While
''' print the string on the browser
Response.Write("<br>" & Str)
''' close the reader
End Sub