0

I am trying to fill an array using a loop in VB. It basically read a .txt file and store all the line in an array. Im getting this error. "Array is used before it has been assigned values".

Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt")
Dim fileName As String
Dim fileReader As StreamReader
Dim strReadFile As String
Dim arrLines() As String
Dim i As Integer = 0
For Each fileName In fileEntries
    fileReader = File.OpenText(fileName)
    Do Until fileReader.Peek = -1
        strReadFile = fileReader.ReadLine()
        arrLines(i) = strReadFile
        i += 1
    Loop
Next

Is there any way I could do this, without pre-defining length of the array? I want the length of array to be number of lines in txt files. Hope i explained this well. Thank you in advance.

Humayun Shabbir
  • 2,961
  • 4
  • 20
  • 33

3 Answers3

0

There is quite a while, in vb6, I used ReDim to dynamically add a new entry in the array in the loop. Inconvenient: slow down the process. Better to count the occurrences needed from the file before creating the array. Hope that helps.

Jeremy
  • 1
  • Or, better yet, use one of the automatic collection classes. I can't remember if VB 6 had any of them (I think it did), but VB.NET certainly does. A *way* better option than `ReDim` if you don't know the size ahead of time. – Cody Gray - on strike Aug 01 '14 at 11:22
0

you can declare arrlines as list:

Dim arrLines As New List(Of String)()

then you can convert to arrLines to array :

arrLines.ToArray()

try this:

Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt")
Dim fileName As String
Dim fileReader As StreamReader
Dim strReadFile As String
Dim arrLines As New List(Of String)()
Dim i As Integer = 0
For Each fileName In fileEntries
    fileReader = File.OpenText(fileName)
    Do Until fileReader.Peek = -1
        strReadFile = fileReader.ReadLine()
        arrLines.Add(strReadFile)
    Loop
Next
arrLines.ToArray()
SysDragon
  • 9,692
  • 15
  • 60
  • 89
renis
  • 171
  • 7
  • 16
0

You can do something like this:

Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt")
Dim fileName As String
Dim fileReader As StreamReader
Dim strReadFile As String
Dim arrLines() As String = {} 'Added this
'Dim i As Integer = 0 'Removed this
For Each fileName In fileEntries
    fileReader = File.OpenText(fileName)
    Do Until fileReader.Peek = -1
        strReadFile = fileReader.ReadLine()
        If arrLines.Length = 0 Then ReDim arrLines(0 To 0) Else ReDim Preserve arrLines(0 To arrLines.Length)
        arrLines(arrLines.Length - 1) = strReadFile
        i += 1
    Loop
Next

Or so...

SammuelMiranda
  • 420
  • 4
  • 29