views:

93

answers:

1

I have the following method to save an Object to a file:

// Save an object out to the disk
public static void SerializeObject<T>(this T toSerialize, String filename)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    TextWriter textWriter = new StreamWriter(filename);

    xmlSerializer.Serialize(textWriter, toSerialize);
    textWriter.Close();
}

I confess I did not write it (I only converted it to a extension method that took a type parameter).

Now I need it to give the xml back to me as a string (rather than save it to a file). I am looking into it, but I have not figured it out yet.

I thought this might be really easy for someone familiar with these objects. If not I will figure it out eventually.

+11  A: 

Use a StringWriter instead of a StreamWriter:

public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    StringWriter textWriter = new StringWriter();

    xmlSerializer.Serialize(textWriter, toSerialize);
    return textWriter.ToString();
}
dtb
That works great! Thanks!
Vaccano