Using pack Uri with resource from a library

0

Support Resource loading in a library, where you have no control over the calling executable. I do not wish to load files from disk.

How can I fix the ConsoleApp2 code so it supports the described scenario?

Based on the Pack Uri documentation, I was able to do this:

What works

  • FontLibrary, a Class Library containing only font files with Build Action: Resource
  • ConsoleApp1, Console Application referencing this FontLibrary.

ConsoleApp1 code

Add reference to WindowsBase runtime assembly.

class Program
{
    static void Main(string[] args)
    {
        // Workaround to register pack://application Uri format
        var notUsedButNeeded  = System.IO.Packaging.PackUriHelper.UriSchemePack;

        var fontFamilies = System.Windows.Media.Fonts.GetFontFamilies(new Uri("pack://application:,,,/"), "/FontLibrary;Component/");

        // This correctly lists the font families contained in the font library
        Console.WriteLine("Number of font families: " + fontFamilies.Count);
    }
}

What doesn't work:

Exception message is

The system cannot find the file specified. (Exception from HRESULT: 0x80070002)'
  • LogicLibrary, a Class Library referecing FontLibrary
  • FontLibrary, a Class Library containing only font files with Build Action: Resource
  • ConsoleApp2, a Console Application referencing LogicLibrary. This represents any consumer of the LogicLibrary, and I cannot add references from this library to the font library, only call LogicLibrary.

ConsoleApp2 code

class Program
{
    static void Main(string[] args)
    {
        new FontLoader().Load();
    }
}

LogicLibrary code

public class FontLoader
{
    public void Load()
    {
        // Workaround to register pack://application Uri format
        var notUsedButNeeded  = System.IO.Packaging.PackUriHelper.UriSchemePack;

         // Raises exception when called from ConsoleApp2, since the APPLICATION = the ConsoleApp2 does not reference the font library.
        var fontFamilies = System.Windows.Media.Fonts.GetFontFamilies(new Uri("pack://application:,,,/"), "/FontLibrary;Component/");

        Console.WriteLine("Number of font families: " + fontFamilies.Count);
    }
}

Similar questions:

Using the correct pack:// URI Format

wpf
asked on Stack Overflow Jan 14, 2021 by Bernard Vander Beken • edited Jan 18, 2021 by Bernard Vander Beken

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0