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 ?