首页 > 解决方案 > 如何在 C# 中保存和加载文本框字体?

问题描述

我想将文本框字体保存在 txt 文件中

这是我的代码

System.IO.File.WriteAllText("path", txtNotepad.Font.ToString());

然后我想通过以下代码从 TXT 文件中读取字体

String fontName = System.IO.File.ReadAllText("path");

如何通过 FontName 更改 TextBox 字体?

标签: c#windowsvisual-studiofile

解决方案


如果您正在使用Font类,请考虑使用提供的FontConverter而不是尝试解析System.Drawing.Font.ToString()自己的结果。

这是一个例子:

// Use the provided converter to get and store a culture-invariant string.
var converter = new FontConverter();
string fontInfo = converter.ConvertToInvariantString(txtNotepad.Font);
File.WriteAllText("path", fontInfo);

// Retrieve the string and set the Font property on your TextBox.
fontInfo = File.ReadAllText("path");
txtNotepad.Font = converter.ConvertFromInvariantString(fontInfo) as Font;

这种方法可以防止您重新发明轮子并为其他文化格式提供处理。


推荐阅读