将数据从文本文件复制到数组

时间:2013-05-24 14:56:59

标签: vb.net

我正在尝试将数据从文本文件复制到数组,我收到错误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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

Dim vString() as string

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

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()