views:

13

answers:

1

I have the following method that I use to serialize various objects to XML. I then write the XML to a file. All the objects have the proper [DataContract] and [DataMember] attributes.

    public static string Serialize<T>(T item)
    {
        var builder = new StringBuilder();
        var serializer = new DataContractSerializer(typeof(T));

        using (var xmlWriter = XmlWriter.Create(builder))
        {
            serializer.WriteObject(xmlWriter, item);
            return builder.ToString();
        }
    }

The serialization works fine, however, I am missing the end of the content. I.e., the string does not contain the full XML document: the end gets truncated. Sometimes the string ends right in the middle of a tag.

There does not seem to be a miximum length that would cause an issue: I have strings of 18k that are incomplete and I have strings of 80k that are incomplete as well.

The XML structure is fairly simple and only about 6-8 nodes deep.

Am I missing something?

+3  A: 

xmlWriter isn't flushed at the point you call ToString(); try:

    using (var xmlWriter = XmlWriter.Create(builder))
    {
        serializer.WriteObject(xmlWriter, item);
    }
    return builder.ToString();

This does the ToString() after the Dispose() on xmlWriter, meaning it will flush any buffered data to the output (builder in this case).

Marc Gravell