检索字体的文件名

El *_*Mac 2 .net c# fonts winforms

我想获取字体的文件名.这不是那么难......我知道,已经存在一个非常类似的问题,但问题的答案不可能就是这样.

我想要做的是通过TCP/IP将Font文件发送给其他客户端,如果他请求的话.我在FontDialog上选择了所需的字体,我可以从框架中获取FontName.我找不到字体文件,我可以说大部分时间都可以使用.

.NET在哪里知道系统上安装了哪些字体?它不能是框架依赖于一直无法运行的解决方案,如CodeProject上的解决方案和Stackoverflow中的建议.必须有一种安全的方法来检索字体文件.FontDialog可以将它们全部列在一个框中,并且安装的字体必须具有其文件的路径.

有兴趣帮助我吗?

在此输入图像描述

Ill*_*ack 7

using System;
using System.Drawing;
using System.Text.RegularExpressions;
using Microsoft.Win32
Run Code Online (Sandbox Code Playgroud)

 

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)