阅读文件流问题

时间:2015-07-02 16:45:52

标签: vb.net filestream

我正在尝试从计算机中读取文件并将其内容输出到文字控件中。它给出了错误:Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.这是我第一次使用FileStream,而且我不是100%关于VB的所有语法,或者甚至是社区首选的阅读方式一个文件,但是有人可以帮我解决这个错误吗?

这是代码:

 Using fs As New FileStream(_path, FileMode.Open, FileAccess.Read)
                Try
                    Dim fileLength As Integer = CInt(fs.Length)
                    Dim buffer() As Byte = New Byte() {fileLength}
                    Dim count As Integer
                    Dim sum As Integer = 0

                    While ((count = fs.Read(buffer, sum, fileLength - sum)) > 0)
                        sum = sum + count
                    End While
                    litOutput.Text = buffer.ToString()
                Catch ex As Exception
                    'TODO: log error
                End Try
            End Using

1 个答案:

答案 0 :(得分:1)

此行错误

Dim buffer() As Byte = New Byte() {fileLength}

它声明一个1字节的数组,您尝试在其中存储文件的长度。您可能已将Option Strict设置为Off,因此您可以在不立即注意到问题的情况下离开。

当然,如果你的文件长度合理且文本文件很简单,那么就不需要这个循环了。只需使用File.ReadAllTextFile.ReadLinesFile.ReadAllLines,顺便说一句,您的代码会在一次调用中读取所有数据,因为FileStream.Read的最后一个参数是字节数从文件读取,表达式fileLength - sum产生一个读取单个调用中所有字节的请求

相反,如果您想要以特定大小的块读取文件 可能你需要

Using fs As New FileStream(path, FileMode.Open, FileAccess.Read)
    Try
        Dim chunkSize = 2000
        Dim fileLength As Integer = CInt(fs.Length)
        Dim buffer(fileLength) as Byte
        Dim blockSize(chunkSize) as Byte
        Dim count As Integer = -1
        Dim pos As Integer = 0

        While count <> 0
            count = fs.Read(blockSize, 0, chunkSize-1)
            Array.Copy(blockSize, 0, buffer, pos, count)
            pos += count
        End While

        litOutput.Text = Encoding.UTF8.GetString(buffer)
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
End Using

请注意,此代码假定您的文件是具有UTF8编码的文本文件 情况并非如此,您可以尝试使用Encoding.ASCII.GetStringEncoding.Unicode.GetString