In my example below, in order for the code to work, place your fonts in the Fonts folder in the exe root.
Also the font name should be of similar format OpenSans-Regular.ttf, where the first part is the name before the dash, and the second part is the style.
I tested the fonts on google fonts, it didn't cause any problems, but there may be fonts with terrible names.
using Microsoft.Win32;
using System;
using System.Drawing.Text;
using System.IO;
private string GetFontName(string fontPath)
{
PrivateFontCollection fontCol = new PrivateFontCollection();
fontCol.AddFontFile(fontPath);
return fontCol.Families[0].Name;
}
public void InstallFonts()
{
// user fonts folder
var fontsPath = $"{Directory.GetCurrentDirectory()}\\Fonts";
// system fonts folder
var fontDestination = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
// import fonts
foreach (var fontFile in Directory.GetFiles(fontsPath))
{
// get font props
var fontFileName = Path.GetFileName(fontFile); // OpenSans-Regular.ttf
var fontName = GetFontName(fontFile); // Open Sans
var fontStyle = fontFileName.Split('-')[1].Split('.')[0]; // Regular, Bold
var fontType = fontFileName.Split('-')[1].Split('.')[1]; // ttf
if (File.Exists($"{fontDestination}\\{fontFileName}"))
{
return;
}
// copy font to dest
File.Copy(Path.Combine(fontsPath, fontFileName), Path.Combine(fontDestination, fontFileName));
// add to registry
using (RegistryKey fontsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", true))
{
fontsKey.SetValue(string.Format("{0} {1} {2}", fontName, fontStyle, fontType == "ttf" ? "(TrueType)" : "(OpenType)"),
fontFileName, RegistryValueKind.String);
}
}
}