Error: Unexpected end of stream. Data might be corrupted

不羁岁月 提交于 2019-12-11 15:58:39

问题


I'm trying something with stream data. I'm getting an error. I have some codes like below. One of both works, but another is not.

This code works properly.

    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();
        }
    }

This code doesn't work.

    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();
        }
    }

What is difference between these codes ? I couldn't find anything. Why is working with FileStream, Why is not working with MemoryStream? Can you explain this please ?


回答1:


Make sure everything is flushed. Move the extraction point down:

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


来源:https://stackoverflow.com/questions/52988343/error-unexpected-end-of-stream-data-might-be-corrupted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!