System.Drawing.Color objects apparently won't serialize with XmlSerializer. What is the best way to xml serialize colors?
Asked
Active
Viewed 1.4k times
4 Answers
34
The simplest method uses this at it's heart:
String HtmlColor = System.Drawing.ColorTranslator.ToHtml(MyColorInstance);
It will just convert whatever the color is to the standard hex string used by HTML which is just as easily deserialized using:
Color MyColor = System.Drawing.ColorTranslator.FromHtml(MyColorString);
That way you're just working with bog standard strings...

BenAlabaster
- 39,070
- 21
- 110
- 151
-
1well then you lose the alpha value. – Марк Павлович Jan 28 '19 at 12:53
-
This is a smart solution. This helped me avoid going through parsing the name to get the RGB values. I find that this is a bug that Color.FromName does not extract the RGB values and sets them all to 0 ... – Zimo Dec 19 '22 at 18:31
18
Final working version:
Color clrGrid = Color.FromArgb(0, 0, 0);
[XmlIgnore]
public Color ClrGrid
{
get { return clrGrid; }
set { clrGrid = value; }
}
[XmlElement("ClrGrid")]
public string ClrGridHtml
{
get { return ColorTranslator.ToHtml(clrGrid); }
set { ClrGrid = ColorTranslator.FromHtml(value); }
}

P a u l
- 7,805
- 15
- 59
- 92
-
2Any better solutions? This kind-a suxx, because for every color you have to write tons of stuff to get it to/from xml. And I am trying to use XML for color-configuring my pretty software :) – Daniel Mošmondor Aug 22 '10 at 20:50
14
We use this:
[Serializable]
public struct ColorEx
{
private Color m_color;
public ColorEx(Color color)
{
m_color = color;
}
[XmlIgnore]
public Color Color
{ get { return m_color; } set { m_color = value; } }
[XmlAttribute]
public string ColorHtml
{
get { return ColorTranslator.ToHtml(this.Color); }
set { this.Color = ColorTranslator.FromHtml(value); } }
public static implicit operator Color(ColorEx colorEx)
{
return colorEx.Color;
}
public static implicit operator ColorEx(Color color)
{
return new ColorEx(color);
}
}

nietras
- 3,949
- 1
- 34
- 38
-
there is another question on the same topic that called this solution a field surrogate. – v.oddou Aug 09 '16 at 09:33
1
You could write a simple wrapper class for Color that exposes the ARGB values as properties. You could translate to/from the colors using from/to ARGB conversions (see docs). Something like:
[Serializable]
public class ColorWrapper
{
private Color color;
public ColorWrapper (Color color)
{
this.color = color;
}
public ColorWrapper()
{
// default constructor for serialization
}
public int Argb
{
get
{
return color.ToARGB();
}
set
{
color = Color.FromARGB();
}
}
}
Probably want an accessor for the color too!
Benefit of this is that the class can be used in all places you have to serialize colors. If you want to make the XML readable (rather than an arbitrary ARGB integer) you could use the to/from HTML methods as described by balabaster.

Jennifer
- 5,148
- 2
- 21
- 19