检索字体的文件名 [英] Retrieve Filename of a font
问题描述
我想获取字体的文件名.这可以这么难...我知道,已经有一个非常相似的问题,但是对这个问题的答案就不可能了.
I would like to get the filename of a font. This can't be that hard... I am aware, there is a very similar question already, but the answer to that question just can't be it.
我想做的是,如果他请求,则通过TCP/IP将字体文件发送给另一个客户端.我通过FontDialog选择所需的字体,可以从框架中获取FontName.我找不到可以说大部分时间都能正常工作的字体文件.
What I want to do is to send a Font file over TCP/IP to an other client, if he requests it. I select the desired font over a FontDialog, I can get the FontName from the framework. I can't find the font file in a way that I can say will work most of the time.
.NET在哪里知道系统上安装了哪些字体?不能说该框架依赖于并非一直有效的解决方案,例如CodeProject上的解决方案以及Stackoverflow中建议的解决方案.必须有一种安全的方法来检索字体文件. FontDialog可以在一个框中列出所有这些字体,并且安装的字体必须具有指向其文件的路径.
Where does .NET know which fonts are installed on the system? It can't be that the framework relies on a solution which does not work all the time, like the solution on CodeProject and suggested in Stackoverflow. There must be a secure way to retrieve the font file. The FontDialog can list them all in a box and the fonts installed must have a path to their file.
有人想帮助我吗?
推荐答案
using System;
using System.Drawing;
using System.Text.RegularExpressions;
using Microsoft.Win32
public static string GetSystemFontFileName(Font font)
{
RegistryKey fonts = null;
try{
fonts = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Fonts", false);
if(fonts == null)
{
fonts = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Fonts", false);
if(fonts == null)
{
throw new Exception("Can't find font registry database.");
}
}
string suffix = "";
if(font.Bold)
suffix += "(?: Bold)?";
if(font.Italic)
suffix += "(?: Italic)?";
var regex = new Regex(@"^(?:.+ & )?"+Regex.Escape(font.Name)+@"(?: & .+)?(?<suffix>"+suffix+@") \(TrueType\)$", RegexOptions.Compiled);
string[] names = fonts.GetValueNames();
string name = names.Select(n => regex.Match(n)).Where(m => m.Success).OrderByDescending(m => m.Groups["suffix"].Length).Select(m => m.Value).FirstOrDefault();
if(name != null)
{
return fonts.GetValue(name).ToString();
}else{
return null;
}
}finally{
if(fonts != null)
{
fonts.Dispose();
}
}
}
这篇关于检索字体的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!