TextWriter序列化为UTF-8字符串

时间:2016-01-28 20:27:45

标签: c# serialization utf-8

我使用TextWriter进行序列化,因为在字符串序列化和文件序列化之间切换很容易:

Serialize to string;

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

序列化为文件;

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

我的问题是,当序列化为字符串时,它会创建一个UTF-16(“?xml version =”1.0“encoding =”utf-16“?”),而TestWriter编码属性是ReadOnly

我试过了:

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();

但它不起作用。它生成此字符串而不是XML文档:“System.IO.StreamWriter”O_o

如何将TextWriter初始化为UTF-8编码

1 个答案:

答案 0 :(得分:6)

使用

代替stringWriter.ToString
string xml = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
return xml;

这会将您编写的内存流转换为标题中带有utf-8的可打印XML。