放气流不读

Deflate stream not reading

DeflateStream.Read 不工作,我正在尝试从压缩内存流中读取,但读取的字节数组参数仍然为空。

        var memoryStream = new MemoryStream();

        var writeStream = new DeflateStream(memoryStream, CompressionLevel.Optimal, true);

        var readStream = new DeflateStream(memoryStream, CompressionMode.Decompress, true);

        var serializedPayloadBytes = Serialize(new Payload { Message = "Payload" });

        var serializedHeaderBytes = Serialize(new PayloadHeader { Length = serializedPayloadBytes.Length });

        var headerSize = serializedHeaderBytes.Length;

        var package = new byte[serializedHeaderBytes.Length + serializedPayloadBytes.Length];

        Buffer.BlockCopy(serializedHeaderBytes, 0, package, 0, serializedHeaderBytes.Length);

        Buffer.BlockCopy(serializedPayloadBytes, 0, package, serializedHeaderBytes.Length, serializedHeaderBytes.Length);

        writeStream.Write(package, 0, package.Length);

        writeStream.Flush();

        writeStream.Close();

        var arr = new byte[serializedHeaderBytes.Length];

        readStream.Read(arr, 0, headerSize);

arr始终为空(所有字节均为零),memoryStream.ToArray()有数据。

MemoryStreams 写入后的位置在流的末尾。如果你想在写入后再次从同一个流中读取,你必须将它设置回 0。

memoryStream.Position = 0;