System.IndexOutOfRangeException:索引超出了数组vb.net无限循环的范围

时间:2014-05-26 14:24:24

标签: vb.net

我正在执行一个无限循环,我对这段代码有疑问:

Dim infiniteCounter As Integer

For infiniteCounter = 1 To 2
    infiniteCounter = 1

    Try
        Dim dataFromClient As String
        Dim bytesFrom(50024) As Byte
        Dim networkStream As NetworkStream = clientSocket.GetStream()

        networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
        dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
    Catch ex As Exception
    End Try
Next

引发问题的具体方法是:

Dim bytesFrom(50024) As Byte

引发此错误:

  

System.IndexOutOfRangeException:索引超出了数组的范围。

知道如何解决这个问题吗?

谢谢

1 个答案:

答案 0 :(得分:0)

在尝试访问之前,添加一项检查以查看是否有以字节为单位的数据:

If bytesFrom IsNot Nothing AndAlso bytesFrom.Length > 0 Then
    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
End If

此外,你应该在try / catch中包装任何可能有异常的特定行,而不是整个代码块(例如获取流,将其读入变量,并解码字节数组)。