Click to See Complete Forum and Search --> : Reading File, Loading to Array


MM007
May 20th, 2008, 09:29 AM
I am a VERY amatuer programmer (VB.NET 2003, Framework 2.0) who made an application that reads a text file, loads all the lines of that text file into an array, and randomly selects one line in that array to display it in a text box in the program.

However, I have had some issues with this code segment:



'Reading Race File for Length
ItemRead = IO.File.OpenText(Dir + "\Race\" + Race + ".txt")
z1 = 0
Do Until ItemRead.Peek() = -1
monkey = ItemRead.ReadLine()
z1 = z1 + 1
Loop
ItemRead.Close()

'randomizing variable
Randomize()
Item = randomgen.Next(0, z1)


'Reading Race File into array
ItemRead = IO.File.OpenText(Dir + "\Race\" + Race + ".txt")
z2 = 0
Do Until z2 = z1
Itemlist(z2) = ItemRead.ReadLine()
z2 = z2 + 1
Loop
ItemRead.Close()


The first thing this segment of code does is access the file, and read each line until the entire document is read through, assigning a number to the counter variable "z1" until the file is finished. The "monkey" variable does nothing whatsoever. I may remove it if it'll work without it.

Next, it picks a random integer between 0 and z1, which will be the line number displayed.

Lastly, it reads the file into an array called "Itemlist(z2)". I use z1 to define the limits of the array, but I get an out of bounds error when it tries to write the array. What am I missing?


Also, while I'm at it, is there an easier way to say "load each line into part of an array, and randomly pick one of those lines"? I've been having array dimension errors since I started on this program.



Also, I should note that when I have a file with 100 lines, this works without fail...but every time I try one with 120 lines, it crashes the application.

MM007
May 20th, 2008, 10:18 AM
...D'OH! I'm an idiot.

I worked for the longest time to fix this, and posted it here, but when I went to edit and post how I was dimensioning my variables, I realized the problem. It's fixed now.


Still, I must wonder...is there a faster and better way to read a single random line of text from a text document of any length?



Right now I'm counting each line, picking a line number from those results at random, loading the whole file to an array (using the line counter as the top limit), and calling that line's number from that array.

dglienna
May 20th, 2008, 10:54 AM
Sure. Look at the bottom sample:

http://www.startvbdotnet.com/files/default.aspx

Marraco
May 20th, 2008, 11:20 AM
...
Still, I must wonder...is there a faster and better way to read a single random line of text from a text document of any length?Add "Imports System.IO" as first line in the Module/Form

to store each line in an array ArrayWithLines do:
Dim fs As FileStream = File.OpenRead(Dir + "\Race\" + Race + ".txt")
Dim sr As New StreamReader(fs)
Dim ArrayWithLines() as String = Split(sr.ReadToEnd(), vbCrLf)
fs.Close()