Search code examples
c#stringcolorsbrush

Converting brush[] to string or brush[] to color[] to string


I am not trying to convert brush to string, but brush array to string.

I need to write a txt file on xml and then I am trying to convert a brush[] into a string, but I do not know how to this directly.

So, I tried to convert first to color and then I would convert color to string.

I am struggling with the first conversion where the code is not allowing me to write this part:

Color[] cor1_local = new Pen(cor_local[i]).Color[];

cor_local is brush[].

Code:

xml.WriteStartElement("cor_frmlocal");
for (int i = 0; i < cor_local.Length; i++)
{
    Color[] cor1_local = new Pen(cor_local[i]).Color[];
    xml.WriteElementString("Cor_local", cor1_local[i].ToArgb().ToString());
}
xml.WriteEndElement();

Solution

  • Try to use that

            xml.WriteStartElement("cor_frmlocal");
            for (int i = 0; i < cor_local.Length; i++)
            {
                xml.WriteElementString("Cor_local", ((SolidBrush)cor_local[i]).Color.ToArgb().ToString());
            }
            xml.WriteEndElement();
    

    the problem was in usage of base Brush class object references that do not contain Color property. To handle that you must cast it back to SolidBrush.

    To convert brush back

    1) create the list of brushes var brushList = new List<Brush>();

    2) read color value as var colorValue = Convert.ToInt32(reader.ReadElementString());

    3) create color from that value var color = Color.FromArgb(colorValue);

    4) create new brush and add it to list list.Add(new SolidBrush(color));

    the result code looks like

    XmlTextReader reader = new XmlTextReader(filename);
    string node_info = "";
    var brushList = new List<Brush>();
    
    while(reader.Read())
    {
        node_info = reader.Name;
    
        if (node_info == "cor_frmlocal")
        {
             var colorValue = Convert.ToInt32(reader.ReadElementString());
             var color = Color.FromArgb(colorValue);
             list.Add(new SolidBrush(color));
        }
    }