【问题标题】:Reading a filestream issue读取文件流问题
【发布时间】:2015-07-02 16:45:52
【问题描述】:

我正在尝试从我的计算机中读取文件并将其内容输出到文字控件中。它给出了错误: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

【问题讨论】:

标签: vb.net filestream


【解决方案1】:

这行写错了

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

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

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

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

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

【讨论】:

  • 谢谢,不知道File.ReadAllText 是一回事。简单多了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
  • 2017-11-30
  • 2014-07-14
  • 2012-05-09
相关资源
最近更新 更多