我遇到异常[System.Runtime.Serialization.Serialization exception:在分析完成之前遇到流的末尾。]关于反序列化字符串,请指导我如何修复此错误。
byte[] compressed;
string content = "afjsklf lkjflfkldsflkfj fa fj lflkf lk kj lkj fldsjf lkflewru pjdslk jsdfi;j klnvmlvnetu iowu lknxvmln3-958u09v lsn";
var compMS = new MemoryStream();
using (var compressor = new GZipStream(compMS, CompressionMode.Compress))
{
new BinaryFormatter().Serialize(compressor, content);
compressed = compMS.ToArray();
}
var decompMS = new MemoryStream(compressed);
using (var decompressor = new GZipStream(decompMS, CompressionMode.Decompress))
{
BinaryFormatter bf = new BinaryFormatter();
decompMS.Position = 0;
string result = (string)bf.Deserialize(decompMS);
}
我也尝试过使用decompMS.Seek(0, SeekOrigin.Begin);
,但异常仍然存在。
http://dotnetfiddle.net/PF7egd
您的代码中有两个问题。
- 在关闭压缩器之前(在第一个使用块之后)执行compMS.ToArray()
- 在解压缩中,您尝试反序列化原始数据,而不是解压缩的数据
看看这把新小提琴:http://dotnetfiddle.net/OryftE
或此处的更正代码:
byte[] compressed;
string content = "afjsklf lkjflfkldsflkfj fa fj lflkf lk kj lkj fldsjf lkflewru pjdslk jsdfi;j klnvmlvnetu iowu lknxvmln3-958u09v lsn";
var compMS = new MemoryStream();
using (var compressor = new GZipStream(compMS, CompressionMode.Compress))
{
new BinaryFormatter().Serialize(compressor, content);
}
compressed = compMS.ToArray();
var decompMS = new MemoryStream(compressed);
using (var decompressor = new GZipStream(decompMS, CompressionMode.Decompress))
{
BinaryFormatter bf = new BinaryFormatter();
decompMS.Position = 0;
string result = (string)bf.Deserialize(decompressor);
}
希望能有所帮助。
谨致问候,Chris