Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize to a variable

The following code sample shows how to serialize/deserialize to a file. How could I modify this to serialize to a variable instead of to a file? (Assume the variable would be passed in to the read/write methods instead of a file name).

    public static void WriteObject(string fileName)
    {
        Console.WriteLine(
            "Creating a Person object and serializing it.");
        Person p1 = new Person("Zighetti", "Barbara", 101);
        FileStream writer = new FileStream(fileName, FileMode.Create);
        DataContractSerializer ser =
            new DataContractSerializer(typeof(Person));
        ser.WriteObject(writer, p1);
        writer.Close();
    }

    public static void ReadObject(string fileName)
    {
        Console.WriteLine("Deserializing an instance of the object.");
        FileStream fs = new FileStream(fileName,
        FileMode.Open);
        XmlDictionaryReader reader =
            XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
        DataContractSerializer ser = new DataContractSerializer(typeof(Person));

        // Deserialize the data and read it from the instance.
        Person deserializedPerson =
            (Person)ser.ReadObject(reader, true);
        reader.Close();
        fs.Close();
        Console.WriteLine(String.Format("{0} {1}, ID: {2}",
        deserializedPerson.FirstName, deserializedPerson.LastName,
        deserializedPerson.ID));
    }
like image 488
Brandon Moore Avatar asked Feb 22 '23 13:02

Brandon Moore


1 Answers

You can change the FileStream to a memory stream and dump it to a byte[].

public static byte[] WriteObject<T>(T thingToSave)
{
    Console.WriteLine("Serializing an instance of the object.");
    byte[] bytes;
    using(var stream = new MemoryStream())
    {
        var serializer = new DataContractSerializer(typeof(T));
        serializer.WriteObject(stream, thingToSave);
        bytes = new byte[stream.Length];
        stream.Position = 0;
        stream.Read(bytes, 0, (int)stream.Length);
    }
    return bytes;

}

public static T ReadObject<T>(byte[] data)
{
    Console.WriteLine("Deserializing an instance of the object.");

    T deserializedThing = default(T);

    using(var stream = new MemoryStream(data))
    using(var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
    {
        var serializer = new DataContractSerializer(typeof(T));

        // Deserialize the data and read it from the instance.
        deserializedThing = (T)serializer.ReadObject(reader, true);
    }
    return deserializedThing;
}
like image 137
scottm Avatar answered Feb 27 '23 08:02

scottm