0

I am using below code to serialize a class.

    public static string SerializeToString<T>(this T toSerialize)
    {
        XmlSerializer serializer = new XmlSerializer(toSerialize.GetType());
        using (StringWriter textWriter = new StringWriter())
        {
            serializer.Serialize(textWriter, toSerialize);
            return textWriter.ToString();
        }

    }

This code is working intermittently. Sometimes it return the serialized string and sometimes not. There is no exception anywhere.

Am I missing something?

Garima
  • 401
  • 5
  • 29

1 Answers1

3

You need to Flush the StringWriter before calling ToString():

public static string SerializeToString<T>(this T toSerialize)
{
    XmlSerializer serializer = new XmlSerializer(toSerialize.GetType());
    using (StringWriter textWriter = new StringWriter())
    {
        serializer.Serialize(textWriter, toSerialize);
        textWriter.Flush();
        return textWriter.ToString();
    }

}

When data is written to a StringWriter it is written to an internal buffer first. Data in the internal buffer is not recognized when calling ToString().

Alternatively you can use the following code:

    public static string SerializeToString<T>(this T toSerialize)
    {
        XmlSerializer serializer = new XmlSerializer(toSerialize.GetType());

        StringBuilder stringBuilder = new StringBuilder();

        using (StringWriter textWriter = new StringWriter(stringBuilder))
        {
            serializer.Serialize(textWriter, toSerialize);
        }

        return stringBuilder.ToString();
    }

Here the StringWriter writes its data to the StringBuilder. By using the using keyword the StringWriter gets closed automatically when leaving the block what forces the StringWriter to flush its data to the given StringBuilder.

Oliver
  • 1,507
  • 1
  • 12
  • 23
  • Could you elaborate a bit? What difference will it make? – Garima Jan 08 '15 at 06:42
  • Have a look [http://stackoverflow.com/questions/2340106/what-is-the-purpose-of-flush-in-java-streams](http://stackoverflow.com/questions/2340106/what-is-the-purpose-of-flush-in-java-streams) for more information about flushing streams (even if it's Java related). – Oliver Jan 08 '15 at 06:53
  • ok but my perception was if we are using "using" code block we dont need it. Using itself will handle flushing and disposing it. – Garima Jan 08 '15 at 07:02
  • 1
    This is correct, but `textWriter.ToString()` is evaluated **before** the `StringWriter` is closed (and flushed) by leaving the `using` block. Have a look here [http://stackoverflow.com/questions/662773/returning-in-the-middle-of-a-using-block](http://stackoverflow.com/questions/662773/returning-in-the-middle-of-a-using-block). – Oliver Jan 08 '15 at 07:08
  • ok I am using the first block of code for now. Will check if issue comes again. Thanks for your answer – Garima Jan 08 '15 at 08:48