Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextWriter serialize to UTF-8 string

I use a TextWriter to serialize, because it's easy to switch between string serialization and file serialization:

Serialize to string;

TextWriter stringWriter = new StringWriter();
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(stringWriter , objetToSerialize)
return stringWriter.ToString();

Serialize to file;

TextWriter fileWriter = new StreamWriter(targetXMLFileName, true, Encoding.UTF8);
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(fileWriter , objetToSerialize)
fileWriter.Close();

My problem is that when serializing to string, it creates a UTF-16 ("?xml version="1.0" encoding="utf-16"?"), and TestWriter encoding property is ReadOnly

I have tried:

var memoryStream = new MemoryStream();
TextWriter stringWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(stringWriter , objetToSerialize)
return stringWriter.ToString();

But it doesn't work. Instead of an XML Document it produces this string: "System.IO.StreamWriter" O_o

How can I initialize the TextWriter to UTF-8 Encoding

like image 810
Kaikus Avatar asked Jan 28 '16 20:01

Kaikus


1 Answers

Instead of stringWriter.ToString, use

string xml = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
return xml;

That will convert the memory stream you wrote to, to a printable XML with utf-8 in the header.

like image 54
EventHorizon Avatar answered Oct 15 '22 03:10

EventHorizon