OrElse
OrElse

Reputation: 9959

How can i get a list of the extended html colors in .NET?

I would love to get a list of the extended html colors, like the ones displayed here

I need both the Color Name and the Html value. Is there any available function in .net?

Upvotes: 0

Views: 325

Answers (3)

Magnus
Magnus

Reputation: 46909

This should do it:

var colors = 
  Enum.GetValues(typeof(KnownColor)).Cast<KnownColor>()
    .Select(k => Color.FromKnownColor(k))
    .Where(k => !k.IsSystemColor)

And if you need hex and name just append:

.Select (k => new 
      { 
         Name = k.Name, 
         Hex = "#" + k.R.ToString("X2") + 
                     k.G.ToString("X2") + 
                     k.B.ToString("X2") 
      });

Upvotes: 1

ivan_pozdeev
ivan_pozdeev

Reputation: 35998

System.Drawing.Color is used for colors (including HTML colors) in .NET. The type has all the CSS3 colors as its static properties so they can be retrieved with reflection. KnownColors includes the list, too, but it also has unrelated colors.

typeof(Color).GetProperties(BindingFlags.Static|BindingFlags.Public)
/*.Where(p=>p.PropertyType == typeof(Color)) */       /* a possible extra precaution:
   * currently, they are all Color.
   * My way is to let the code break on casting instead if anything changes
   * to draw attention to the change.
   * You may also validate the total number against the spec (141)
   * (the table in the spec actually has 148 entries 'cuz it has both
   * "gray" and "grey" spellings). */
.Select(p=>(Color)(p.GetValue(null,null)))

Note that the list includes Color.Transparent which you may or may not want - since it's a valid CSS color, too.

Upvotes: 1

Andrew
Andrew

Reputation: 7880

Here is another way to do it, the shortest and easiest I have found:

foreach (Color col in new ColorConverter().GetStandardValues())
{
    if (!col.IsSystemColor)
        Console.WriteLine("{0} {1}", col.Name, ColorTranslator.ToHtml(Color.FromArgb(col.ToArgb())));
}

Another way to get the html code:

Console.WriteLine("{0} #{1}", col.Name, Color.FromArgb(col.ToArgb()).Name.Substring(2).ToUpper());

Credits to these answers: https://stackoverflow.com/a/3821216/2321042 and https://stackoverflow.com/a/28777828/2321042

Upvotes: 0

Related Questions