49

我在使用内存流进行序列化时遇到问题。这是我的代码:

/// <summary>
/// serializes the given object into memory stream
/// </summary>
/// <param name="objectType">the object to be serialized</param>
/// <returns>The serialized object as memory stream</returns>
public static MemoryStream SerializeToStream(object objectType)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, objectType);
    return stream;
}

/// <summary>
/// deserializes as an object
/// </summary>
/// <param name="stream">the stream to deserialize</param>
/// <returns>the deserialized object</returns>
public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object objectType = formatter.Deserialize(stream);
    return objectType;
} 

我得到的错误如下:流不是有效的二进制格式。起始内容(以字节为单位)是:blah....

我不确定是什么导致了错误。任何帮助将不胜感激。

调用示例:

Dog myDog = new Dog();
myDog.Name= "Foo";
myDog.Color = DogColor.Brown;

MemoryStream stream = SerializeToStream(myDog)

Dog newDog = (Dog)DeserializeFromStream(stream);
4

4 回答 4

59

这段代码对我有用:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

类型是这样的:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

实用方法是:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}
于 2012-04-30T21:14:41.387 回答
6

使用方法从内存中序列化和反序列化集合对象。这适用于集合数据类型。此方法会将任何类型的集合序列化为字节流。创建一个单独的类SerilizeDeserialize并添加以下两个方法:

public class SerilizeDeserialize
{

    // Serialize collection of any type to a byte stream

    public static byte[] Serialize<T>(T obj)
    {
        using (MemoryStream memStream = new MemoryStream())
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            binSerializer.Serialize(memStream, obj);
            return memStream.ToArray();
        }
    }

    // DSerialize collection of any type to a byte stream

    public static T Deserialize<T>(byte[] serializedObj)
    {
        T obj = default(T);
        using (MemoryStream memStream = new MemoryStream(serializedObj))
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            obj = (T)binSerializer.Deserialize(memStream);
        }
        return obj;
    }

}

如何在你的类中使用这些方法:

ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);

ArrayList arrayListMemDes = new ArrayList();

arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);

Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
    Console.WriteLine(item);
}
于 2018-08-29T19:31:48.870 回答
3

BinaryFormatter在某些特定情况下可能会产生无效的输出。例如,它将省略未配对的代理字符。接口类型的值也可能存在问题。阅读此文档页面,包括社区内容。

如果您发现您的错误持续存在,您可能需要考虑使用 XML 序列化程序,如DataContractSerializerXmlSerializer.

于 2012-04-30T21:49:21.780 回答
1

它可以通过使用System.Text.Json在 .Net 6 中使用 System.Text.Json 轻松完成;

Examlple ex = JsonSerializer.Deserialize<Example>(ms);
Console.WriteLine(ex.Value);

class Example
{
    string Value {get; set; }
}

请参阅进行序列化。

于 2021-10-26T08:40:34.897 回答