Encoding.UTF8.GetString

时间:2016-07-28 10:52:32

标签: .net vb.net

此功能

Public Function UnzipString(ByVal bByteBuffer() As Byte) As String

    Dim lastBytes(3) As Byte

    Array.Copy(bByteBuffer, bByteBuffer.Length - 4, lastBytes, 0, 4)
    Dim sBufferLength As Integer = BitConverter.ToInt32(lastBytes, 0)

    Dim sBuffer(sBufferLength - 1) As Byte
    Dim ms As New System.IO.MemoryStream(bByteBuffer)
    Dim ds As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress, True)
    ds.Read(sBuffer, 0, sBufferLength)
    Return System.Text.Encoding.UTF8.GetString(sBuffer)

End Function

在Return语句,GetString调用上停止出现Out of Memory错误。 sBuffer非常大,里面有165 MB(字节)数据,但我还是喜欢它。任何人都可以想到一种方法来使这个工作适用于大型数据集吗?

1 个答案:

答案 0 :(得分:0)

我最后编写了另一个将字节数组直接写入文件的子程序,从而避免了整个解压缩内容的任何内存存在:

Public Sub UnzipStringToFile(bByteBuffer() As Byte, sFileName As String)

    '   This avoids the "out of memory" error when using UnzipString

    Using _
        ms As New System.IO.MemoryStream(bByteBuffer),
        ds As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress, True),
        fs As System.IO.FileStream = System.IO.File.Create(sFileName)

        ds.CopyTo(fs)
        ds.Close()

    End Using

End Sub