Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 610
Jader Dias Avatar asked Apr 10 '12 13:04

Jader Dias


2 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()));
    }
}
like image 100
carlosfigueira Avatar answered Oct 11 '22 20:10

carlosfigueira


Have you tried using XmlWriterSettings? Something like

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

Specify the Encoding you require.

like image 31
Phil Avatar answered Oct 11 '22 20:10

Phil