接收 System.IndexOutOfRangeException 错误

Receiving System.IndexOutOfRangeException Error

我编写了计算文本文件行数并创建包含行的文件夹的代码。 例如如果有这样的文字

Text1
Text2
Text3

文件夹将由这些文本组成。这是抛出 System.IndexOutOfRangeException 错误

的代码
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

它可以完美地创建文件夹,但是每当它完成创建文件夹时,它都会抛出 System.IndexOutOfRangeException File.ReadAllLines 错误。有人可以帮我解决这个问题吗?

考虑像这样更改代码结构

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

这样更好,因为首先将数组加载到内存中,并且不会在 for 循环的每次迭代中计算数组的长度

节日快乐

您的异常是因为您试图读取位于 lineCount 位置的数组,而实际上,您永远不应该读取过去的 lineCount - 1,这是数组的最后一个位置。

因此将您的 For 语句更改为这样可以避免异常:

For i = 0 to lineCount - 1

但是,我真的不建议您现在设置代码的方式,因为您实际上每次都在重新阅读 整个 文件 你调用 File.ReadAllLines(),你甚至在循环中也这样做。对于大文件,性能影响将是巨大的。那可不好,完全没有必要。

相反,使用 For Each 循环将是一种更简洁的编写方式:

For Each RAL In File.ReadAllLines(TempPath & "EAB\EAB.txt")
    Directory.CreateDirectory(startPath & "\Test\" & RAL & "\")
Next