views:

19

answers:

0
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace XmlTest
{
    class TestClass : IXmlSerializable
    {
        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            var data = new byte[3];
            reader.ReadStartElement();
            reader.ReadElementContentAsBase64(data, 0, data.Length);
        }

        public void WriteXml(XmlWriter writer)
        {
            var data = new byte[] { 1, 2, 3 };
            writer.WriteBase64(data, 0, data.Length);
        }

        public static void Main()
        {
            var serializer = new DataContractSerializer(typeof(TestClass));

            var stringWriter = new StringWriter();
            using (var writer = XmlWriter.Create(stringWriter))
            {
                serializer.WriteObject(writer, new TestClass());
            }

            var stringReader = new StringReader(stringWriter.ToString());
            using (var reader = XmlReader.Create(stringReader))
            {
                serializer.ReadObject(reader, true);
            }
        }
    }
}

The ReadElementContentAsBase64 line throws NotSupportedException with message:

ReadElementContentAsBase64 method is not supported on this XmlReader. Use CanReadBinaryContent property to find out if a reader implements it.

(I checked, and CanReadBinaryContent returns true)

I'm using the Microsoft .NET 3.5 framework implementation.

What could possibly cause this?

Note: I'm intentionally mixing DataContractSerializer with IXmlSerializable. I realize that the more common approach for DataContractSerializer is to make my class a [DataContract].

Edit: I'm now using a workaround:
Convert.FromBase64String(reader.ReadElementContentAsString())
Still, I wonder why the regular way fails.