0

我正在尝试将数据从文本文件复制到数组,但出现错误Index was outside the bounds of the array

    Dim vstring(-1) As String
    Dim vid(-1) As String
    Dim index As Integer
    Dim vText As String = ""
    Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"

    Dim vAvgValue As Integer
    Dim vErrorMsg As String = ""
    If (Txt_IdNumber.Text).Length = 5 Then

        Dim rvSR As New IO.StreamReader(vFileName)
        Do While rvSR.Peek <> -1
            vText = rvSR.ReadLine()
            vstring = vText.Split(",")
            vid(index) = vstring(0)'error 
            index = index + 1
        Loop
4

2 回答 2

1
Dim vstring() as String
Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"

If Txt_IdNumber.Text.Length = 5 Then
    Using rvSR As New IO.StreamReader(vFileName)
        vstring = rvSR.ReadLines().Select(Function(s) s.Split(","c)(0)).ToArray()
    End Using
End If
于 2013-05-24T15:08:27.423 回答
0

首先,您可能应该将 vstring 声明为一个未调整大小的数组。像这样:

Dim vString() as string

其次,由于您不知道需要多少行,因此将 vid 声明为列表。像这样:

Dim vid as List(of string)

然后,在拆分字符串之前,您应该确保它实际上包含一个逗号。像这样:

    Do While rvSR.Peek <> -1
        vText = rvSR.ReadLine()
        If vText.Contains(",") Then
           vstring = vText.Split(",")
           vid.add(vstring(0)) 
        End If
    Loop
    'at the end, you can convert vid from a list to an array, if you want 
    Dim arr() as string = vid.ToArray()
于 2013-05-24T15:15:27.283 回答