views:

44

answers:

2

Hi All,
I had a quick question regarding the datacontractserializer. Maybe it's more of a stream question. I found a piece of code that writes the xml to a filestream. I basically don't want the file and just need the string output.

    public static string DataContractSerializeObject<T>(T objectToSerialize)
    {

        var fs = new FileStream("test.xml", FileMode.OpenOrCreate);
        var serializer = new DataContractSerializer(typeof(T));
        serializer.WriteObject(fs, objectToSerialize);
        fs.Close();
        return fs.ToString();
    }

fs.ToString() is obviously not what I'm looking for. What stream or writer etc, can I use just to return the proper string and not create a file? I did look at the XML the filestream created and it's exactly what I'm looking for. The XmlSerializer wrote the XML a bit strange and I prefer the output of the DataContractSerializer in this case. Can anyone point me in the right direction?

Thanks A Bunch,
~ck in San Diego

+3  A: 

Something like this - put your output into a MemoryStream and then read that back in:

public static string DataContractSerializeObject<T>(T objectToSerialize)
{
    MemoryStream memStm = new MemoryStream();
    var serializer = new DataContractSerializer(typeof(T));
    serializer.WriteObject(memStm, objectToSerialize);

    memStm.Seek(SeekOrigin.Begin, 0);
    string result = new StreamReader(memStm).ReadToEnd();
    return result;
}
marc_s
A: 
/// <summary>
/// Converts this instance to XML.
/// </summary>
/// <returns>XML representing this instance.</returns>
public string ToXml()
{
    var serializer = new DataContractSerializer(this.GetType());
    var output = new StringWriter();
    using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })
    {
        serializer.WriteObject(writer, this);
    }
    return output.GetStringBuilder().ToString();
}
Pat