C# 从二进制文件反序列化具有结构成员的类
我对二进制文件的反序列化结构有问题。我的结构有另一个结构作为属性:C# 从二进制文件反序列化具有结构成员的类,c#,deserialization,C#,Deserialization,我对二进制文件的反序列化结构有问题。我的结构有另一个结构作为属性: [Serializable()] public struct Record : ISerializable { public SensorInfo SensorInfo; public List<short[]> Frames; public Record(SerializationInfo info, StreamingContext ctxt) { this.Fr
[Serializable()]
public struct Record : ISerializable
{
public SensorInfo SensorInfo;
public List<short[]> Frames;
public Record(SerializationInfo info, StreamingContext ctxt)
{
this.Frames = (List<short[]>)info.GetValue("Frames", typeof(List<short[]>));
this.SensorInfo = (SensorInfo)info.GetValue("SensorInfo", typeof(SensorInfo));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("Frames", this.Frames);
info.AddValue("SensorInfo", this.SensorInfo);
}
}
我正在将序列化程序与以下代码一起使用:
static public class RecordSerializer
{
static RecordSerializer()
{
}
public static void SerializeRecord(string filename, Record recordToSerialize)
{
Stream stream = File.Open(filename, FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, recordToSerialize);
stream.Close();
}
public static Record DeSerializeRecord(string filename)
{
Record recordToSerialize;
Stream stream = File.Open(filename, FileMode.Open);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
recordToSerialize = (Record)bFormatter.Deserialize(stream);
stream.Close();
return recordToSerialize;
}
}
序列化工作正常,我得到一个输出文件。但当我尝试反序列化它时,我从bFormatter得到唯一的异常。反序列化和反序列化失败
Frequency not found.
流不是空的,我检查了这个
谢谢您的建议。您正在为属性
Frequency
和FramePixelDataLength
添加空白,如“Frequency”和“FramePixelDataLength”
使用以下命令:
info.AddValue("Frequency", this.Frequency);
info.AddValue("FramePixelDataLength", this.FramePixelDataLength);
而不是:
info.AddValue("Frequency ", this.Frequency);
info.AddValue("FramePixelDataLength ", this.FramePixelDataLength);
保存该文件后,您是否更改了second
struct
?此外,在info.AddValue(“Frequency”,即this.Frequency)中有一个额外的空间用于命名Frequency
代码>只需额外的空间即可
info.AddValue("Frequency ", this.Frequency);
info.AddValue("FramePixelDataLength ", this.FramePixelDataLength);