System.Drawing.Color serialization

The Person class includes a HairColor property that stores a Color object. Because a Color cannot be automatically serialized/deserialized using the .NET System.Xml.Serialization.XmlSerializer class, the Color object is saved to the XML file as an HTML string, and converted back into a Color when the XML file is loaded.

sing System;
using System.Drawing;
using System.Xml.Serialization;
 
 
//To support binary serialization you need to 
// add the "[Serializable]" attribute
[Serializable]
public class Person
{
    private Color _HairColor = Color.Empty;
        
    // Initializes a new instance of the Person class.
    // (required for serialization)
    public Person()
    {
            
    }
        
        
    // Set serialization to ignore this property
        // because the 'HairColorHtml' property
        // is used instead to serialize
        // the 'HairColor' Color as an HTML string.
    [XmlIgnoreAttribute()]
    public Color HairColor
    {
        get
        {
            return _HairColor;
        }
        set
        {
            _HairColor = value;
        }
    }
        
        
    // Serializes the 'HairColor' Color to XML.
    [XmlElement("HairColor")]
    public string HairColorHtml
    {
        get 
        { 
            return
                ColorTranslator.ToHtml(_HairColor);
        }
        set 
        { 
            _HairColor = ColorTranslator.FromHtml( value );
        }
    }
        
}


 
 
 

Leave a Reply