12

写入流时,DataContractSerializer使用不同于 Unicode-16 的编码。如果我可以强制它写入/读取 Unicode-16,我可以将它存储在 SQL CE 的binary列中并使用SELECT CONVERT(nchar(1000), columnName). 但它的方式是,我无法阅读它,除非以编程方式。

我可以更改使用的编码System.Runtime.Serialization.DataContractSerializer吗?

4

2 回答 2

13

DataContractSerializer 的WriteObject方法具有写入 aStream或 a XmlWriter(and XmlDictionaryWriter) 的重载。重载将Stream默认为 UTF-8,因此您需要使用另一个。使用以 UTF-16 编写 XML 的 XML Writer 实例可以满足您的需求,因此您可以执行@Phil 建议的操作,也可以使用XmlDictionaryWriter.CreateTextWriter您将 anEncoding.Unicode作为参数传递给它的 writer 返回。

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()));
    }
}
于 2012-04-10T15:37:31.197 回答
5

您是否尝试过使用 XmlWriterSettings?就像是

var s = new DataContractSerializer (typeof(Thing));

using(var wr = XmlTextWriter.Create(
    @"test.xml", new XmlWriterSettings{Encoding=Encoding.UTF32}))
{
    s.WriteObject(wr, new Thing{Foo="bar"});
}

public class Thing
{   
    public string Foo { get; set; }
}

指定您需要的编码。

于 2012-04-10T13:37:10.580 回答