我有以下代码:
MemoryStream resultStream = new MemoryStream();
string users = ""//Really long string goes here
BinaryFormatter bFormatter = new BinaryFormatter();
using (MemoryStream assignedUsersStream = new MemoryStream())
{
bFormatter.Serialize(assignedUsersStream, users);
assignedUsersStream.Position = 0;
using (var compressionStream =
new DeflateStream(resultStream, CompressionLevel.Optimal))
{
assignedUsersStream.CopyTo(compressionStream);
Console.WriteLine("Compressed from {0} to {1} bytes.",
assignedUsersStream.Length.ToString(),
resultStream.Length.ToString());
}
}
事情是resultStream
总是空的!
我在这里做错了什么?
答案 0 :(得分:10)
将您的验证WriteLine放在使用之外。缓冲区尚未刷新。
using (DeflateStream compressionStream = new DeflateStream(resultStream, CompressionLevel.Optimal))
{
assignedUsersStream.CopyTo(compressionStream);
//Console.WriteLine("Compressed from {0} to {1} bytes.",
// assignedUsersStream.Length.ToString(), resultStream.Length.ToString());
}
Console.WriteLine("Compressed from {0} to {1} bytes.",
assignedUsersStream.Length, resultStream.ToArray().Length);
除此之外,你不需要在写作线上的所有ToString()
。
PS:所有BinaryFormatter都使用字符串写入带有长度前缀的字节。如果你不需要前缀(我的猜测),它可能会变成:
string users = "";//Really long string goes here
byte[] result;
using (MemoryStream resultStream = new MemoryStream())
{
using (DeflateStream compressionStream = new DeflateStream(resultStream,
CompressionLevel.Optimal))
{
byte[] inBuffer = Encoding.UTF8.GetBytes(users);
compressionStream.Write(inBuffer, 0, inBuffer.Length);
}
result = resultStream.ToArray();
}
反过来也很简单,但你需要估计最大长度来创建读缓冲区:
string users2 = null;
using (MemoryStream resultStream = new MemoryStream(result))
{
using (DeflateStream compressionStream = new DeflateStream(resultStream,
CompressionMode.Decompress))
{
byte[] outBuffer = new byte[2048]; // need an estimate here
int length = compressionStream.Read(outBuffer, 0, outBuffer.Length);
users2 = Encoding.UTF8.GetString(outBuffer, 0, length);
}
}
答案 1 :(得分:9)
这是因为DeflateStream
在关闭之前不会将数据刷新到基础流。关闭后,resultStream
将包含压缩数据。请注意,默认情况下,DeflateStream
会在基础流关闭时关闭它,但您不希望这样,因此您需要为true
参数传递leaveOpen
。此外,您不需要2个内存流,您可以直接序列化到compressionStream
:
string users = ""; //Really long string goes here
BinaryFormatter bFormatter = new BinaryFormatter();
using (MemoryStream resultStream = new MemoryStream())
{
using (DeflateStream compressionStream = new DeflateStream(resultStream, CompressionLevel.Optimal, true))
{
bFormatter.Serialize(compressionStream, users);
Console.WriteLine(resultStream.Length); // 0 at this point
}
Console.WriteLine(resultStream.Length); // now contains the actual length
}
答案 2 :(得分:3)
从最初的答案(我没有足够的学分投票)
将控件WriteLine置于使用
之外
这是不完整和误导性的。一旦DeflateStream超出范围,DeflateStream就会关闭底层的resultStream。因此resultStream.Length抛出
Unhandled Exception: System.ObjectDisposedException: Cannot access a closed Stream.
Thomas Levesque是正确的=>同时将leaveOpen
设置为true。
一个有趣的问题,HH和TL提出了一些好的观点。