Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This XmlWriter does not support base64 encoded data

I have a class like this:

public class Data
{
    public string Name { get; set; }
    public int Size { get; set; }
    public string Value { get; set; }

    [NonSerialized] public byte[] Bytes;
}

When a List<Data> hits the serialization method below, it occasionally dies with

InvalidOperationException "This XmlWriter does not support base64 encoded data."

As you can see, I am not directly encoding anything, just using the default serialization mechanism.

private static XDocument Serialize<T>( T source )
{
    var target = new XDocument( );
    var s = new XmlSerializer( typeof( T ) );
    using( XmlWriter writer = target.CreateWriter( ) )
    {
        s.Serialize( writer, source );
    }
    return target;
}

The data will have Name properties that are English words separated by underscores. The Value property will by similar except with added math operators or numbers (they are mathematical expressions).

Does anyone know what is causing it and how I can correct it?

like image 393
µBio Avatar asked Oct 15 '22 01:10

µBio


1 Answers

Use [XmlIgnore] instead of [NonSerialized]. The latter is for the SOAP and binary formatters, according to MSDN:

When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized. For example, you can use this attribute to prevent the serialization of sensitive data.

The target objects for the NonSerializedAttribute attribute are public and private fields of a serializable class. By default, classes are not serializable unless they are marked with SerializableAttribute. During the serialization process all the public and private fields of a class are serialized by default. Fields marked with NonSerializedAttribute are excluded during serialization. If you are using the XmlSerializer class to serialize an object, use the XmlIgnoreAttribute class to get the same functionality.

Mind you, I'm surprised your original code even compiles - when I try it, it says that [NonSerialized] can only be applied to fields...

like image 149
Jon Skeet Avatar answered Oct 21 '22 05:10

Jon Skeet