2

I'm developing a UWP app with C# to preview font files from the user's local disk. I'm using SharpDX libraries to read the .ttf file content and query the different font properties. My question is:

How can I set a TextBlock FontFamily to the loaded font?

Of course setting the FontFamily property with the loaded font name doesn't work as the loaded font is not necessary installed on the system.

Please help.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Leisvan
  • 105
  • 1
  • 7

1 Answers1

2

You can't load the font as long as you don't have full file system privileges.

But what you can do is the following:

I. Let the user pick a font file from the system (I guess you did already complete this task)

II. Copy the retrieved StorageFile into your app's sandbox.

async Task<StorageFile> ImportFont(StorageFile file)
{
  StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("fontcache", CreationCollisionOption.OpenIfExists);
  return await file.CopyAsync(folder, file.Name, NameCollisionOption.ReplaceExisting);
}

III. Next, create the path to the imported file (here are all available URI schemes listed)

StorageFile importedFile = await ImportFont(userPickedFile);
string fontPath = "ms-appdata:///local/fontcache/" + importedFile.Name;

IV. Create the font family based on your path

string fontName = sharpDXFont.Name; // this is the name SharpDX has extracted
FontFamily family = new FontFamily(fontPath + "#" + fontName);

V. That's it!

Don't forget to clean up your local folder, when the font is not need anymore.

tobi.at
  • 1,267
  • 13
  • 18
  • 1
    I apologize for my recklessness. I have delete the answer that you do not agree. – Nico Zhu Sep 18 '18 at 14:25
  • 1
    As you saw this answer is very old, the uwp run in sandbox, and it could not access disk directly, my comment is incorrect. – Nico Zhu Sep 18 '18 at 14:29