0

I wrote code that counts lines in text file and creates folders with lines. For example If there is text like this

Text1
Text2
Text3

The folders would be made with those texts. Here's the code that throws System.IndexOutOfRangeException Error

Dim lineCount = File.ReadAllLines(TempPath & "EAB\EAB.txt").Length
For i = 0 To lineCount Step 1
    Dim RAL As String = File.ReadAllLines(TempPath & "EAB\EAB.txt")(i)
    Directory.CreateDirectory(startPath & "\Test\" & RAL & "\")
Next

It creates folders perfectly but whenever it finishes creating folder it throws System.IndexOutOfRangeException Error In File.ReadAllLines. Can anybody help me to fix this?

T.S.
  • 18,195
  • 11
  • 58
  • 78
asomethings
  • 45
  • 2
  • 10
  • Duplicate of [What is IndexOutOfRangeException and how do I fix it?](http://stackoverflow.com/questions/20940979/what-is-indexoutofrangeexception-and-how-do-i-fix-it) – Bjørn-Roger Kringsjå Dec 12 '15 at 08:56

2 Answers2

3

Your exception is caused because you are trying to read the array at position lineCount, when in fact, you should never read past lineCount - 1, which is that last position of the array.

So changing your For statement to this would avoid the exception:

For i = 0 to lineCount - 1

However, I would really advise against the way you have setup your code right now, because you are actually re-reading the entire file every time you invoke File.ReadAllLines(), which you do even inside the loop. For a big file, the performance impact would be huge. That's not good and completely unnecessary.

Instead, using a For Each loop would be a much cleaner way of writing this:

For Each RAL In File.ReadAllLines(TempPath & "EAB\EAB.txt")
    Directory.CreateDirectory(startPath & "\Test\" & RAL & "\")
Next
sstan
  • 35,425
  • 6
  • 48
  • 66
1

Consider changing your code structure like such

Dim lines as String() = File.ReadAllLines(...);
Dim count as Integer = lines.Length;

for i as Integer = 0 To count Step 1
   Dim thisLine as String = lines(i)

   //Stuff
next

This is better because the array is loaded into memory first and the length of the array is not calculated with every iteration of the for loop

Happy Holidays

Jake Psimos
  • 640
  • 3
  • 10