How to change the DataContractSerializer text encoding?
.net, c#, character-encoding, serialization, wcf
Solution
The DataContractSerializer's `WriteObject` method has overloads which write to a `Stream` or to a `XmlWriter` (and `XmlDictionaryWriter`). The `Stream` overload will default to UTF-8, so you'll need to use another one. Using a XML Writer instance which writes the XML in UTF-16 do what you needs, so you can either do what @Phil suggested, or you can use the writer returned by `XmlDictionaryWriter.CreateTextWriter` for which you pass an `Encoding.Unicode` as a parameter.
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()));
}
}
Problem
When writing to a stream the `DataContractSerializer` uses an encoding different from Unicode-16. If I could force it to write/read Unicode-16 I could store it in a SQL CE's `binary` column and read it with `SELECT CONVERT(nchar(1000), columnName)`. But the way it is, I can't read it, except programatically. Can I change the encoding used by `System.Runtime.Serialization.DataContractSerializer`?