(二)序列化中的“二进制流不包含有效的BinaryHeader”错误?

时间:2010-08-08 17:43:17

标签: c# .net serialization

我在“Object to byte not working”之前创建了一个帖子。 我解决了用户说我的问题,但仍有问题。

错误消息:未找到反序列化“WindowsFormsApplication1.Form1 + Item”类型的对象的构造函数。;

void start()
{

 Item item = new Item();
 item.files.Add(@"test");
 byte[] b = ObjectToByteArray(item);  
     Item k = Desriles(b);

}


[Serializable]
public class Item : ISerializable
{
    public Item()
    {
        files = new List<string>();
        Exclude = false;
        CleanEmptyFolder = false;
    }
    public List<string> files;
    public string MusicProfileName;
    public bool Exclude;

    #region ISerializable Members

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("files", files);
        info.AddValue("MusicProfileName", MusicProfileName);
        info.AddValue("Exclude", Exclude);
    }

    #endregion
}

public byte[] ObjectToByteArray(object _Object)
{
    using (var stream = new MemoryStream())
    {
        // serialize object 
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, _Object);

        // get a byte array
        var bytes = new byte[stream.Length];
        using (BinaryReader br = new BinaryReader(stream))
        {
            bytes = br.ReadBytes(Convert.ToInt32(stream.Length));
        }

        return bytes;
    }

}


    public Item Desriles(byte[] items)
    {
        using (MemoryStream stream = new MemoryStream())
        {

            stream.SetLength(items.LongLength);
            stream.write(items, 0, items.Length);
            var formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);

            object item = formatter.Deserialize(stream); // Here I will get error
            return (Item)item;


        }
    }

4 个答案:

答案 0 :(得分:2)

在本节中:

using (MemoryStream stream = new MemoryStream())
{
    stream.SetLength(items.LongLength);
    stream.Read(items, 0, items.Length);
    [...]
    object item = formatter.Deserialize(stream);

您似乎正在创建一个新的内存流,然后尝试从中读取,并从中Deserialize

当然失败了。该流为空

答案 1 :(得分:2)

序列化代码无法正常工作,您忘记将流重置为开头。更好的鼠标陷阱:

    public byte[] ObjectToByteArray(object _Object) {
        using (var stream = new MemoryStream()) {
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, _Object);
            return stream.ToArray();
        }
    }

反序列化代码可以类似地简化:

    public Item Desriles(byte[] items) {
        using (MemoryStream stream = new MemoryStream(items)) {
            var formatter = new BinaryFormatter();
            return (Item)formatter.Deserialize(stream);
        }
    }

并且您不需要GetObjectData()。

答案 2 :(得分:0)

abelenky提出了一个很好的观点,但我不认为你的:

public byte[] ObjectToByteArray(object _Object)

也可以。

答案 3 :(得分:0)

感谢All:

我发现问题:我应该以 ISerializable

为基础