使用二进制文件中的struct成员反序列化类

时间:2013-10-21 19:03:44

标签: c# deserialization

我在二进制文件中遇到反序列化结构的问题。我的结构有另一个结构作为属性:

[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);
    }
}

SensorInfo结构:

[Serializable]
public struct SensorInfo : ISerializable
{
    public double Frequency;
    public int FramePixelDataLength;
    public int FrameWidth;
    public int FrameHeight;

    public SensorInfo(SerializationInfo info, StreamingContext ctxt)
    {
        this.Frequency = (double)info.GetValue("Frequency", typeof(double));
        this.FramePixelDataLength = (int)info.GetValue("FramePixelDataLength", typeof(int));
        this.FrameWidth = (int)info.GetValue("FrameWidth", typeof(int));
        this.FrameHeight = (int)info.GetValue("FrameHeight", typeof(int));

    }

    public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
    {
        info.AddValue("Frequency ", this.Frequency);
        info.AddValue("FramePixelDataLength ", this.FramePixelDataLength);
        info.AddValue("FrameWidth", this.FrameWidth);
        info.AddValue("FrameHeight", this.FrameHeight);
    }
}

我正在使用带有此代码的序列化程序:

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.

Stream不为空,我查了一下。

感谢任何想法。

1 个答案:

答案 0 :(得分:0)

您要为属性FrequencyFramePixelDataLength添加空格,例如“Frequency”和“FramePixelDataLength”。

使用此:

info.AddValue("Frequency", this.Frequency);
info.AddValue("FramePixelDataLength", this.FramePixelDataLength);

而不是:

info.AddValue("Frequency ", this.Frequency);
info.AddValue("FramePixelDataLength ", this.FramePixelDataLength);