Open and Read files in VB.Net

July 15, 2010 - 15:17

To read the entire contents of a file first we must open the file and specify the access mode by using the System.IO namespace. This class also allows various file operations such as delete, copy, and checking for the existance of a file.

The basic code to open a file and read in the entire contents is shown below:

<%@Import Namespace="System.IO" %>

Dim document as string
Dim myfilestream As New _
System.IO.FileStream("test.txt", _
System.IO.FileMode.Open, _
System.IO.FileAccess.Read, _
System.IO.FileShare.None)

Dim myreader As New System.IO.StreamReader(myfilestream)
document=myreader.ReadToEnd()
myreader.Close()
myfilestream.Close()


This will read in the contents of the text.txt file and enter the contents into the document string.

If you wish to read in a single line at a time then instead of ReadToEnd() then use ReadLine()



© 2011 simplevb.net