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
.