125

Possible Duplicate:
How to get Color from Hex color code using .NET?

I want to convert a string like #FFFFFF to System.Drawing.Color. How do you do that?

2
  • stackoverflow.com/questions/2109756/… Commented Aug 28, 2012 at 8:57
  • 2
    Voting to reopen, the dup question deals with a different type of Color structure. Commented Apr 1, 2015 at 18:09

3 Answers 3

295
string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);

Note: the hash is important!

Sign up to request clarification or add additional context in comments.

3 Comments

What about in UWP, where there is no System.Drawing namespace?
@AdrianK use the answer from codeteq. It work for me from NetStandard 2.0
This worked for me: item.BackgroundColor = Color.FromHex(line.s_BackGroundCol);
30

You can do

var color =  System.Drawing.ColorTranslator.FromHtml("#FFFFFF");

Or this (you will need the System.Windows.Media namespace)

var color = (Color)ColorConverter.ConvertFromString("#FFFFFF");

1 Comment

When I convert white, I get not the white color exactly.
15

Remove the '#' and do

Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
                         System.Globalization.NumberStyles.AllowHexSpecifier));

3 Comments

There are options available which do no require the conversion to a numeric value, this is an unnecessary step. The OP states it's a string
The other solutions are converting the string into a numeric value too, they are just doing it internally. If this is a question of optimization, then performance testing would be required to see how Color.FromArgb() w/ int.Parse() compare to ColorConvertor.ConvertFromString() and ColorTranslator.FromHtml().
Won't that have an alpha value of 0?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.