Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I effectively persist a .Net font object?

Usecase: The user makes font customizations to an object on the design surface, that I need to load/save to my datastore. I.e. settings like Bold, Italics, Size, Font Name need to persisted.

Is there some easy (and reliable) mechanism to convert/read back from a string representation of the font object (in which case I would need just one attribute)? Or is multiple properties combined with custom logic the right option?

like image 968
Gishu Avatar asked Sep 23 '08 01:09

Gishu


1 Answers

Use TypeConverter:

Font font = new Font("Arial", 12, GraphicsUnit.Pixel);

TypeConverter converter = TypeDescriptor.GetConverter(typeof (Font));

string fontStr = converter.ConvertToInvariantString(font);

Font font2 = (Font) converter.ConvertFromString(fontStr);

Console.WriteLine(font.Name == font2.Name); // prints True

If you want to use XML serialization you can create Font class wrapper which will store some subset of Font properties.

Note(Gishu) - Never access a type converter directly. Instead, access the appropriate converter by using TypeDescriptor. Very important :)

like image 134
aku Avatar answered Nov 08 '22 07:11

aku