Search code examples
c#asp.netuwpuwp-xamlwebfonts

Issue in adding font to Application.Current.Resources after downloading font file at runtime in UWP?


I have requirement of downloading font files at runtime and apply that Font to the text. I successfully download the font file and added it to the Windows.ApplicationModel.Package.Current.InstalledLocation (Debug\AppX\Assets)after added it to the Application.Current.Resources but the font not applying to the text but if I add manually font file to the Apps Assets instead of (Debug\AppX\Assets) folder then the font is getting applied successfully. Here is complete code what I did

//Downloading font file
HttpClient client = new HttpClient();
var response = await client.GetByteArrayAsync("https://webfonts.sample.com/archivoblackregular/font.ttf");

//Creating font file in public space and writing all response to the file
StorageFolder PublicFontFolder = ApplicationData.Current.LocalFolder;
StorageFile fontfile = await PublicFontFolder.CreateFileAsync(fontFamily+".ttf",CreationCollisionOption.ReplaceExisting);
await File.WriteAllBytesAsync(fontfile.Path, response);

//Moving that file to the Assets folder as we don't have direct access to create file in Assets folder
StorageFolder AssetsFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
await fontfile.MoveAsync(AssetsFolder, fontfile.Name, NameCollisionOption.ReplaceExisting);
StorageFile AssetsFontFile = await AssetsFontFolder.GetFileAsync(fontfile.Name);

//Adding that font file to application resources
Application.Current.Resources[fontFamily] = new FontFamily(AssetsFontFile.Path + "#" + fontFamily);

How can I complete my requirement?


Solution

  • I've figured out what i was doing wrong, instead of doing this

    Application.Current.Resources[fontFamily] = new FontFamily(AssetsFontFile.Path + "#" + fontFamily);

    i had to do is if file is in local folder then Application.Current.Resources[fontFamily] = new FontFamily("ms-appdata:///<folder>/<subfolder>/<file>" + "#" + fontFamily);,

    if it is in assets folder then Application.Current.Resources[fontFamily] = new FontFamily("ms-appx:///<subfolder>/<file>" + "#" + fontFamily);