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));
    }
                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;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With