Is there an easy way (in .Net) to test if a Font is installed on the current machine?
Here's how I would do it:
private static bool IsFontInstalled(string name)
{
using (InstalledFontCollection fontsCollection = new InstalledFontCollection())
{
return fontsCollection.Families
.Any(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));
}
}
One thing to note with this is that the Name
property is not always what you would expect from looking in C:\WINDOWS\Fonts. For example, I have a font installed called "Arabic Typsetting Regular". IsFontInstalled("Arabic Typesetting Regular")
will return false, but IsFontInstalled("Arabic Typesetting")
will return true. ("Arabic Typesetting" is the name of the font in Windows' font preview tool.)
As far as resources go, I ran a test where I called this method several times, and the test finished in only a few milliseconds every time. My machine's a bit overpowered, but unless you'd need to run this query very frequently it seems the performance is very good (and even if you did, that's what caching is for).
string fontName = "Consolas";
float fontSize = 12;
using (Font fontTester = new Font(
fontName,
fontSize,
FontStyle.Regular,
GraphicsUnit.Pixel))
{
if (fontTester.Name == fontName)
{
// Font exists
}
else
{
// Font doesn't exist
}
}
Going off of GvS' answer:
private static bool IsFontInstalled(string fontName)
{
using (var testFont = new Font(fontName, 8))
return fontName.Equals(testFont.Name, StringComparison.InvariantCultureIgnoreCase);
}
In my case I need to check font filename with extension
ex: verdana.ttf = Verdana Regular, verdanai.ttf = Verdana Italic
using System.IO;
IsFontInstalled("verdana.ttf")
public bool IsFontInstalled(string ContentFontName)
{
return File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), ContentFontName.ToUpper()));
}
How do you get a list of all the installed fonts?
var fontsCollection = new InstalledFontCollection();
foreach (var fontFamily in fontsCollection.Families)
{
if (fontFamily.Name == fontName) {...} \\ check if font is installed
}
See InstalledFontCollection class for details.
MSDN:
Enumerating Installed Fonts
Thanks to Jeff, I have better read the documentation of the Font class:
If the familyName parameter specifies a font that is not installed on the machine running the application or is not supported, Microsoft Sans Serif will be substituted.
The result of this knowledge:
private bool IsFontInstalled(string fontName) {
using (var testFont = new Font(fontName, 8)) {
return 0 == string.Compare(
fontName,
testFont.Name,
StringComparison.InvariantCultureIgnoreCase);
}
}