How to use text files with

Hi there!

This is a small tutorial on using files with
As uses new technologies it will be strange for some new developers!

First we must import the Syste.IO Class
Imports System.IO

Reading Text Files:
the easiest way to open a text file is with the System.IO.File.OpenText() method.

Code:'Dim your StreamReader
Dim TextFileStream As System.IO.TextReader

'Load the textfile into the stream
TextFileStream = System.IO.File.OpenText("C:\MyTextFile.txt")

'Read to the end of the file into a String variable.
Dim MyFileContents As String = TextFileStream.ReadToEnd

'Close the Stream object

The above code will open a text file on your C drive called MyTextFile.txt. It will load all of the text into a string variable called MyFileContents.
It won't create a file of that name if it doesn't already exist (and will throw an exception which you should handle - but see later in the FAQ for how to create a new file).

Creating Text Files:

Code:'Dim your Text Writer
Dim TW As System.IO.TextWriter

'Create a Text file and load it into the TextWriter
TW = System.IO.File.CreateText("C:\MyTextFile.txt")

'Write a line
TW.WriteLine("Hello World")

'Write another line
TW.WriteLine("Hello World Again")

'Flush the text to the file

'Close the File

Append to an existing Text file:

Code:'Dim your Stream Writer or Text Writer.
Dim SW As IO.TextWriter

'Open a file for Appending
SW = IO.File.AppendText("C:\MyTextFile.txt")

'Write a line to the bottom of the text file
SW.WriteLine("This is another line added to the bottom of the text file.")

'Flush to the file

'Close the object

Here is how to get a random line from a text file with the smallest code I can think of.
Extracting One Line From a File:

Code:Dim RandomNumber As New Random()
Dim Tr As IO.TextReader = System.IO.File.OpenText("C:\MyTextFile.txt")
Dim FileLines() As String = Split(Tr.ReadToEnd(), vbCrLf)
Dim MyRandomLine As String = FileLines(RandomNumber.Next(0, UBound(FileLines)))

If you know what line you want to access then you can make it smaller like this :

Dim Tr As IO.TextReader = System.IO.File.OpenText("C:\MyTextFile.txt")
Dim MyFileLine As String = Split(Tr.ReadToEnd(), vbCrLf)(3)

Note that the above code will return the fourth line from the file. It's zero based, so you would enter (0) for line 1, (1) for line 2 and so on.

If you need more, I advice you to focus on the MSDN Library!


Post a Comment