How to check if there is an already installed Source

Asked

Viewed 355 times

5

I have a C# program that checks if there is a source already installed or not, but it is not working properly:

I’m trying with the following code

if (File.Exists(@"C:\Windwos\Fonts\Agency FB"))

inserir a descrição da imagem aqui

Would anyone know how to verify by source name?

  • But does it make a mistake? Or does it always say that it does not find?

  • 1

    No error occurs, just returns false in the if.

  • 2

    This your "Windwos" path is wrong, the correct one should be "C: Windows Fonts".

  • Not even correct in this case, because I can install and register a source in any folder of the system. Fonts is the default folder for this, but it is not required. It is right to call the OS functions for this.

1 answer

6


You can use the class InstalledFontCollection and find out if your source is in the collection:

public bool FonteExiste(string aMinhaFonte)
{
    var fonts = new InstalledFontCollection();
    return fonts.Families.Any(f => f.Name.Equals(aMinhaFonte, StringComparison.OrdinalIgnoreCase));
}

Performance may vary as it is necessary to run the collection to find the source. An alternative solution will be:

public bool FonteExiste(string aMinhaFonte) 
{
    using (Font fontTester = new Font(aMinhaFonte,
                                      10,
                                      FontStyle.Regular,
                                      GraphicsUnit.Pixel))
    {
        return fontTester.Name.Equals(aMinhaFonte, StringComparison.OrdinalIgnoreCase);
    }
}

This form is based on the fact that if the source you seek does not exist, the class Font will put the source Microsoft Sans Serif as default. Dai test if the font name created is equal to the desired font name.

However this way will only look for fonts that have the normal style (instead of bold/italic/etc) defined.

To conclude, if the performance is not critical, prefer the first solution since it is more complete.

EDIT: The two examples in Dotnetfiddle.

  • 1

    thank you very much, I was testing the first option, I will give a tested in the second too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.