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?


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
        public string Name { get; set; }
        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

how do you open a PDF at a specific page from the command line? (OSX or Linux)

osx pdf command-line

I want to open a PDF document at a specific page from the command line, sort of like vim +n [file]. Is there any way to do that in OSX, with any PDF reader program?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.