.net 使用内存流进行序列化/反序列化

egdjgwm8  于 2023-01-14  发布在  .NET
关注(0)|答案(4)|浏览(179)

我在使用内存流进行序列化时遇到了一个问题。下面是我的代码:

/// <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;
}

我得到的错误如下:流不是有效的二进制格式。起始内容(以字节为单位)为:废话
我不太清楚是什么原因导致了这个错误。任何帮助都将不胜感激。
电话示例:

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

MemoryStream stream = SerializeToStream(myDog)

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

mnemlml81#

这个代码对我有效:

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;
}
hrirmatl

hrirmatl2#

使用方法序列化和反序列化内存中的集合对象。此方法适用于集合数据类型。此方法将任何类型的集合序列化为字节流。创建一个单独的类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);
}
qmb5sa22

qmb5sa223#

BinaryFormatter在某些特定情况下可能会产生无效输出。例如,它将省略不成对的代理项字符。它还可能在接口类型的值方面存在问题。请阅读此documentation page,包括社区内容。
如果您发现错误持续存在,您可能需要考虑使用XML序列化器,如DataContractSerializerXmlSerializer

93ze6v8z

93ze6v8z4#

这可以通过使用System.Text.Json在.Net 6中使用System.Text.Json轻松实现;

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

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

有关序列化,请参阅此。

相关问题