i have an application where my user changes font and font color for different labels etc and they save it to a file but i need to be able to convert the font of the specified label to a string to be written to file, and then when they open that file my program will convert that string back into a font object. How can this be done? I haven't found anywhere that shows how it can be done.
thank you
bael
It is easy to go back and forth from a font to a string and back with the System.Drawing.FontConverter class. For example:
var cvt = new FontConverter();
string s = cvt.ConvertToString(this.Font);
Font f = cvt.ConvertFromString(s) as Font;
You can serialize the font class to a file.
See this MSDN article for details of how to do so.
To serialize:
private void SerializeFont(Font fn, string FileName)
{
using(Stream TestFileStream = File.Create(FileName))
{
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(TestFileStream, fn);
TestFileStream.Close();
}
}
And to deserialize:
private Font DeSerializeFont(string FileName)
{
if (File.Exists(FileName))
{
using(Stream TestFileStream = File.OpenRead(FileName))
{
BinaryFormatter deserializer = new BinaryFormatter();
Font fn = (Font)deserializer.Deserialize(TestFileStream);
TestFileStream.Close();
}
return fn;
}
return null;
}
Quite simple really if you want to make it readable in the file:
class Program
{
static void Main(string[] args)
{
Label someLabel = new Label();
someLabel.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Strikeout | FontStyle.Italic);
var fontString = FontToString(someLabel.Font);
Console.WriteLine(fontString);
File.WriteAllText(@"D:\test.txt", fontString);
var loadedFontString = File.ReadAllText(@"D:\test.txt");
var font = StringToFont(loadedFontString);
Console.WriteLine(font.ToString());
Console.ReadKey();
}
public static string FontToString(Font font)
{
return font.FontFamily.Name + ":" + font.Size + ":" + (int)font.Style;
}
public static Font StringToFont(string font)
{
string[] parts = font.Split(':');
if (parts.Length != 3)
throw new ArgumentException("Not a valid font string", "font");
Font loadedFont = new Font(parts[0], float.Parse(parts[1]), (FontStyle)int.Parse(parts[2]));
return loadedFont;
}
}
Otherwise serialization is the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With