Error: Unexpected end of stream. Data might be corrupted

Error: Unexpected end of stream. Data might be corrupted

我正在尝试使用流数据。我收到一个错误。我有一些代码如下。两个作品中的一个,另一个不是。

这段代码工作正常。

    private static void Main_2()
    {
        {
            var i = 1000000;

            var bf = new BinaryFormatter();
            var ms = new MemoryStream();
            bf.Serialize(ms, i);
            ms.Position = 0;
            Stream mem = File.Create("test.lz4");
            LZ4EncoderStream target = LZ4Stream.Encode(mem);
            ms.CopyTo(target);
            target.Dispose();
            ms.Dispose();
            mem.Dispose();
        }

        {
            Stream source = File.OpenRead("test.lz4");
            LZ4DecoderStream target = LZ4Stream.Decode(source);
            var mem = new MemoryStream();
            target.CopyTo(mem);

            var bf = new BinaryFormatter();
            mem.Position = 0;
            var i = (int)bf.Deserialize(mem);

            mem.Dispose();
            target.Dispose();
            source.Dispose();
        }
    }

此代码无效。

    private static void Main()
    {
        var m = new MemoryStream();

        {
            var i = 1000000;

            var bf = new BinaryFormatter();
            var ms = new MemoryStream();
            bf.Serialize(ms, i);
            ms.Position = 0;
            Stream mem = new MemoryStream();
            LZ4EncoderStream target = LZ4Stream.Encode(mem);
            ms.CopyTo(target);
            m = new MemoryStream(((MemoryStream)mem).ToArray());
            target.Dispose();
            ms.Dispose();
            mem.Dispose();
        }

        {
            Stream source = m;
            LZ4DecoderStream target = LZ4Stream.Decode(source);
            var mem = new MemoryStream();
            target.CopyTo(mem);

            var bf = new BinaryFormatter();
            mem.Position = 0;
            var i = (int)bf.Deserialize(mem);

            mem.Dispose();
            target.Dispose();
            source.Dispose();
        }
    }

这些代码有什么区别?我找不到任何东西。为什么使用 FileStream,为什么不使用 MemoryStream?你能解释一下吗?

确保所有内容都已刷新。下移撤离点:

//m = new MemoryStream(((MemoryStream)mem).ToArray());
target.Dispose();
ms.Dispose();
mem.Dispose();
m = new MemoryStream(((MemoryStream)mem).ToArray());