How do I effectively persist a .Net font object?
-
02-07-2019 - |
Question
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?
Solution
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 :)
OTHER TIPS
In the project I'm working on, I went with the multiple properties.
I save the font to a database table by breaking out its name, size, style and unit and then persist those values.
Recreating the font on demand once these values are retrived is a snap.
What type of datastore do you need to persist this in? If it is just user settings that can be persisted in a file you could serialise the font object to a settings file in either binary or xml (if you want to be able to edit the config file directly). The serialisation namespaces (System.Xml.Serialization and System.Runtime.Serialization) provide all the tools to do this without writing custom code.
MSDN Site on XML Serialisation: XML Serialization in the .Net Framework
[EDIT]So aparrently the font object isn't serialisable. oops :( Sorry.