我正在尝试反序列化流,但总是收到此错误“解析完成之前遇到流结束”?
这是代码:
//Some code here
BinaryFormatter b = new BinaryFormatter();
return (myObject)b.Deserialize(s);//s---> is a Stream object that has been fill up with data some line over here
有人有想法吗?
尝试将流的位置设置为 0,并且不使用对象而是使用对象类型。
BinaryFormatter b = new BinaryFormatter();
s.Position = 0;
return (YourObjectType)b.Deserialize(s);
确保序列化已完成,并且序列化类型与反序列化类型匹配(即,如果您使用 BinaryFormatter 进行反序列化,请确保使用 BinaryFormatter 进行序列化)。另外,请确保您序列化的流确实完成了序列化,使用 Stream.Flush() 或类似的方法。
我抛出了同样的异常,直到我将 [Serialized] 标签添加到我正在序列化的类中:)
然后一切都很完美。
就我而言,我使用:
stream.Seek(0, SeekOrigin.Begin);
在我序列化流之后,在我反序列化流之前,流工作的魅力。希望这有帮助!
我花了 5 个小时,遇到了流结束错误并丢失了数据(GzipStream 中没有明显的功能:您应该仅在刷新 GzipStream 之后才使用底层流)。
工作代码的完整示例:
using System;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
string large = LargeJsonContent.GetBigObject();
string base64;
using (var readStream = new MemoryStream())
using (var writeStream = new MemoryStream())
{
using (GZipStream compressor = new GZipStream(writeStream, CompressionMode.Compress, true)) //pay attention to leaveOpen = true
{
var formatter = new BinaryFormatter();
formatter.Serialize(readStream, large);
Console.WriteLine($"After binary serialization of JsonString: {readStream.Length} bytes");
readStream.Position = 0;
readStream.CopyTo(compressor);
}
Console.WriteLine($"Compressed stream size: {writeStream.Length} bytes");
writeStream.Position = 0;
byte[] writeBytes = writeStream.ToArray();
base64 = Convert.ToBase64String(writeBytes);
}
////
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, base64);
Console.WriteLine($"Size of base64: {stream.Length} bytes");
}
Console.WriteLine("---------------------");
////
string large2;
var bytes = Convert.FromBase64String(base64);
using (var readStream = new MemoryStream())
{
readStream.Write(bytes, 0, bytes.Length);
readStream.Position = 0;
Console.WriteLine($"Compressed stream size: {readStream.Length} bytes");
using (var writeStream = new MemoryStream())
{
using (GZipStream decompressor = new GZipStream(readStream, CompressionMode.Decompress, true)) //pay attention to leaveOpen = true
{
decompressor.CopyTo(writeStream);
writeStream.Position = 0;
}
var formatter = new BinaryFormatter();
large2 = (string)formatter.Deserialize(writeStream);
}
}
Console.WriteLine(large == large2);
Console.WriteLine($"large:{large.Length} | large2:{large2.Length}");
}
}
}
如果您没有执行以下操作,请检查您的发件人代码
NetworkStream strm = client.GetStream(); // the stream
formatter.Serialize(strm, status); // the serialization process
strm.Close();// Remove this code, this was the culprit in my case
您创建的类必须具有[Serialized]。
我也有同样的问题。如果我正在序列化的类中有其他自定义对象,我必须确保这些自定义对象也是[可序列化]的,以使二进制格式化程序序列化/反序列化工作时不会出现此错误。