How to change the DataContractSerializer text encoding?

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?

Answers


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

Need Your Help

Should I make HTML Anchors with 'name' or 'id'?

html html5 hyperlink fragment-identifier

When one wants to refer to some part of a webpage with the "http://example.com/#foo" method, should one use

System.IO.FileSystemWatcher to monitor a network-server folder - Performance considerations

.net performance filesystemwatcher

I want to watch a folder tree on a network server for changes. The files all have a specific extension. There are about 200 folders in the tree and about 1200 files with the extension I am watching...