XmlSerialize直接到GZipStream会在Decompression上抛出幻数异常

时间:2011-03-28 04:58:50

标签: serialization xml-serialization compression gzipstream

我正在尝试将对象序列化为XML,但是我的对象是包含许多记录的通用列表,并导致序列化程序占用大量内存。所以我尝试使用以下代码直接序列化到GZipStream:

Dim formatter As XmlSerializer = XmlSerializerFactory.GetSerializerForType(_type)
Using _ms As New MemoryStream()
    Using gzStream As New GZipStream(_ms, CompressionMode.Compress, True)

        _ms.Position = 0
        formatter.Serialize(gzStream, obj)
        _ms.Position = 0
        gzStream.Flush()
        gzStream.Close()
    End Using

    _ms.Position = 0
    Dim decompressData() As Byte
    Using gzStream As New GZipStream(_ms, CompressionMode.Decompress)
        ReDim decompressData(9000 - 1) 'this number doesn't matter, the data in my test sample is small
        Dim Len As Integer = gzStream.Read(decompressData, 0, decompressData.Length)
    End Using
End Using

但是,当我尝试将数据读入decompressData数组时,我遇到了InvalidDataException The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.

当我首先序列化为单独的内存流然后压缩该流时,例如:

Dim formatter As XmlSerializer = XmlSerializerFactory.GetSerializerForType(_type)
Using _ms As New MemoryStream()
    Dim uc_fileBytes() As Byte
    Dim uc_len As Integer
    Using _ms101 As New MemoryStream()
        formatter.Serialize(_ms101, obj)
        uc_fileBytes = _ms101.GetBuffer()
        uc_len = _ms101.Length
    End Using
    Using gzStream As New GZipStream(_ms, CompressionMode.Compress, True)
        _ms.Position = 0
        gzStream.Write(uc_fileBytes, 0, uc_len)
        gzStream.Flush()
        gzStream.Close()
    End Using

    Dim decompressData() As Byte
    Using gzStream As New GZipStream(_ms, CompressionMode.Decompress)
        ReDim decompressData(9000 - 1)
        Dim Len As Integer = gzStream.Read(decompressData, 0, decompressData.Length)
    End Using
End Using

它没有错误地工作正常。但是,当我直接序列化到GZipStream时,为什么会失败?

1 个答案:

答案 0 :(得分:0)

问题的原因是因为GZipStream在写入时对MemoryStream的行为(显然)不同。它不能很好地处理分页写入。