简体   繁体   中英

How to obtain a font file path in c#?

I have to assign to a string variable the path of a font selected through the FontDialog.

How can I accomplish this task?

string fontTextPath = fontDialog.Font // and then?

Or are there other methods?

Are you sure about that ffmpeg need path of the font and not the name of it ? Most of the time components and libraries use the name of the font or it's object and work by it.

if the component need font name or font object it's so simple as something like :

DrawText('Sample Text, fontDialog1.Font);

but if you really need to get the path of the selected font in FontDialog :

private List<string> GetFilesForFont(string fontName)
{
    var fontNameToFiles = new Dictionary<string, List<string>>();

    foreach (var fontFile in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Fonts)))
    {
        var fc = new PrivateFontCollection();

        if (File.Exists(fontFile))
            fc.AddFontFile(fontFile);

        if ((!fc.Families.Any()))
            continue;

        var name = fc.Families[0].Name;

        // If you care about bold, italic, etc, you can filter here.
        if (! fontNameToFiles.TryGetValue(name, out var files))
        {
            files = new List<string>();
            fontNameToFiles[name] = files;
        }

        files.Add(fontFile);
    }

    if (!fontNameToFiles.TryGetValue(fontName, out var result))
        return null;

    return result;
}

and use it this way :

    if (fontDialog1.ShowDialog() == DialogResult.OK)
    {
        string fontName = fontDialog1.Font.Name;
        var fontFiles = GetFilesForFont(fontName);
    }

Assuming you are using an OpenFileDialog because your supplied code is using an object called fontDialog...

using (OpenFileDialog fontDialog = new OpenFileDialog())
{
    DialogResult result = fontDialog.ShowDialog();
    if (result == DialogResult.OK)
    {
        string file = fontDialog.FileName;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM