当写入流时,DataContractSerializer使用与Unicode-16不同的编码.如果我可以强制它编写/读取Unicode-16,我可以将其存储在sql CE的二进制列中,并使用SELECT CONVERT(nchar(1000),columnName)读取它).但是它的方式,我不能读它,除了程序设计.
可以更改System.Runtime.Serialization.DataContractSerializer使用的编码吗?
解决方法
DataContractSerializer的WriteObject方法具有写入Stream或XmlWriter(和XmlDictionaryWriter)的重载. Stream过载将默认为UTF-8,因此您需要使用另一个.使用在UTF-16中编写
XML的
XML Writer实例可以执行您所需要的操作,因此您可以执行@Phil建议的操作,也可以使用XmlDictionaryWriter.CreateTextWriter返回的作者作为参数传递Encoding.Unicode .
public class StackOverflow_10089682 { [DataContract(Name = "Person",Namespace = "http://my.namespace")] public class Person { [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } } public static void Test() { MemoryStream ms = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms,Encoding.Unicode); DataContractSerializer dcs = new DataContractSerializer(typeof(Person)); Person instance = new Person { Name = "John Doe",Age = 33 }; dcs.WriteObject(writer,instance); writer.Flush(); // Don't forget to Flush the writer here Console.WriteLine("Decoding using UTF-16: {0}",Encoding.Unicode.GetString(ms.ToArray())); } }