写入流时,DataContractSerializer
使用与Unicode-16不同的编码。如果可以强制它写入/读取Unicode-16,则可以将其存储在SQL CE的binary
列中,并使用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
返回的writer,并为其传递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()));
}
}