索引超出了数组的范围[VB.NET]

时间:2015-02-18 09:19:59

标签: vb.net visual-studio vb.net-2010

嗨,我是VB的新手,也是学习的过程。这种错误有时会发生,有时候不会发生,我觉得很奇怪。 我收到错误Index was outside the bounds of the array,指向Button30.Text = Split(newestversion, vbCrLf)(**1**)

我的动机是从在线托管文本文件中逐行阅读。 例如,

label1.text = line 1 of the text file
label2.text = line 2 of the text file

这就是我想要的。

这是我目前的代码(EDITED):

Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("direct link to my online txt file")
Dim response As System.Net.HttpWebResponse = request.GetResponse

Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream)

Dim stringReader As String

        stringReader = sr.ReadLine()
        Button10.Text = stringReader


        Dim newestversion As String = sr.ReadToEnd
        Dim currentversion As String = Application.ProductVersion

        Dim part() As String = Split(newestversion, vbCrLf)

        If part.Length < 10 Then
            ' not enough items in the array. You could also throw and exception or do some other stuff here
            Label10.Text = "beta"
            Exit Sub
        End If


        'updates new episode numbers on buttons
        Button20.Text = part(0)
        Button30.Text = part(1)
        Button40.Text = part(2)
        Button50.Text = part(3)
        Button60.Text = part(4)
        Button70.Text = part(5)
        Button80.Text = part(6)
        Button90.Text = part(7)
        Button100.Text = part(8)
        Button110.Text = part(9)

    End If

谢谢!!

1 个答案:

答案 0 :(得分:1)

您将String分割为line breaks。这为您提供了一个数组,String中的每一行都有一个条目。但是,您不检查此数组是否包含您期望的项目数量。你可以这样做:

Dim newestversion As String = sr.ReadToEnd
Dim currentversion As String = Application.ProductVersion

Dim part() As String = Split(newestversion, vbCrLf)

If part.Length < 10 Then
    ' not enough items in the array. You could also throw and exception or do some other stuff here
    MsgBox(String.Format("Array only has {0} items", part.Length))
    Exit Sub 
End If

'updates new episode numbers on buttons
Button20.Text = part(0)
Button30.Text = part(1)
Button40.Text = part(2)
...

编辑更新的问题

如果你遇到这样的问题,只需系统地处理它并获得尽可能多的信息。首先,您必须检查是否确实从远程源获得了所需的数据。为此,请添加一些日志记录(例如MsgBox(newestversion)或真实日志文件)。 检查您获得的数据是否符合预期。如果没有,那么您的请求/响应代码已经存在问题,这与我提供的解决方案完全不同。如果newestversion正常,请通过打印part()数组来检查拆分是否有效。也许服务器使用不同的操作系统,或者只使用vbCr作为换行而不是vbCrlf。如果拆分也有效,那么你就完成了。