Filling an Array from a Text File

daryl4356

Member
Joined
May 30, 2006
Messages
13
Programming Experience
Beginner
i am just finishing off my first app in vb.net and i would just liek to make it a bit more easier to maintain in future.

I would need to fill an array which could be hundreds to thousands of lines long so adding to this would be easier by just adding a line to a text file.

I have searched through the fourm and all posts refer to more complex methods, how do you you just do a simple line by line text file to an array, and how would you call it in your method?

I know you would use the Streamreader to do this, though the posts on teh forum i have got this far.

Dim sr As New StreamReader("c:/example.txt")
Dim line As String
Do
line = sr.ReadLine()
'How do i populate the array here.
Loop Until line Is Nothing
sr.Close()

I am just unsure what i need to do to populate a part of the array, I think above where i have commented it is where I need to do this.

and will I call it any differently in my method?

it's 4:22am my time so can't say have not tried lol:D :D .

any help would be greatly appreciated
 
filling an array from a text file is actually rather easy:

and in this case, i would actually recamend using an ArrayList instead of an Array, once you start using an ArrayList I'm sure you'll see why:
VB.NET:
Dim TextFileArray As New ArrayList
Dim sr As New StreamReader("C:\Example.txt")
Do While sr.Peek <> -1 'If there arent any lines left, peek returns a -1
  TextFileArray.Add(sr.ReadLine)
Loop
sr.Close
and there ya go, each element (sorted by index) in the arraylist is a line of the text file, to write the textfile simply:
VB.NET:
Dim sw As New StreamWriter("C:\Example.txt")
For Each str As String In TextFileArray
  sw.WriteLine(str)
Next str
sw.Close
 
I'm a bit late on the scene here but can I point out that reading a text file into an array in VB 2005 is REALLY easy:
VB.NET:
Dim lines As String() = IO.File.ReadAllLines("file path here")
 
The two different discussions "read file into array" and "get random item from array" is hereby split to separate threads :)
 
Back
Top