0

Fill an array from a text file

Pretty early in my programming exploration I found that hard coding information into applications was bad practice – if for no other reason than that if any of this information changed it would require editing the actual application an re-publishing. A way to get around this is to read information from an external file on startup.

To do this we will make use of the streamreader and point it at a text file to load information into a string or array.

Whenever code deals with external files specifically it is good practice to wrap this in a try catch statment to stop the application from crashing and give information on any errors.

Streamreader

Firstly insert the following at the beginning of your code to enable the use of the streamreader:

Imports System.IO

Once this is in place the streamreader can be called and used very simply as below (the string “Test” could be declared privately or publicly to make it available elsewhere). Notice that after use the streamreader has been closed, this must be done every time the streamreader is called.

Dim sr As StreamReader=File.OpenText(Application.StartupPath & "\Info.txt")
Dim Text As String
 
Text = sr.ReadToEnd
 sr.Close()

Whilst the above code is perfectly usable and could be used as is in a sub it directly calls a hard coded filename which will throw an error if that file does not exist. As the system.IO namespace has been imported an if statement using file.exists can easily be used to get around this problem (as we’re referencing the same filename twice it can be declares as a variable for convenience)

Dim Filename As String = Application.StartupPath & "\Info.txt"
Dim sr As StreamReader = File.OpenText(Filename)
Dim Text As String
If File.Exists(Filename) Then
Text = sr.ReadToEnd
End If
 
sr.Close()

Loading Arrays

As the streamreader information can be treated as a string it can be directly loaded into an array using the string.split method to load each line as a separate array item (as above the array can be declared privately or publicly).

Dim Filename As String = Application.StartupPath & "\Info.txt"
Dim sr As StreamReader = File.OpenText(Filename)
Dim DataArray() As String
 
If File.Exists(Filename) Then
    DataArray = sr.ReadToEnd.Split(vbCrLf)
End If
 
sr.Close()

When referring to external files it is good practice to put your code into a try catch statement as picking out more complex information usually requires specific formatting within the files being referred to which can cause errors when this formatting hasn’t been applied properly.

JBaker

Joi is an IT Development Analyst working in London and a consummate technophile. Whilst he isn't coding he can be found reacquainting himself with his guitars, spinning poi, looking for climbing walls or chasing the latest shiny thing to cross his field of vision.

Leave a Reply

Your email address will not be published. Required fields are marked *