views:

47

answers:

1

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?

+3  A: 

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...

Jon Skeet
That was easy, will accept when SO lets me ... :) Thanks
BioBuckyBall
The 'only applied to fields'...sorry, that was artifact of me sanitizing the code before posting. Edited the question to fix it.
BioBuckyBall
@Lucas: Fair enough :) Glad it worked.
Jon Skeet