C# PrivateFontCollection无法在.Net Core下添加内存字体

C# PrivateFontCollection无法在.Net Core下添加内存字体,c#,.net-core,gdi+,system.drawing,privatefontcollection,C#,.net Core,Gdi+,System.drawing,Privatefontcollection,我需要向PrivateFontCollection添加一组字体。 出于某种原因,应使用AddMemoryFont函数完成此任务 var fontCollectionFromMemory = new PrivateFontCollection(); var fontCollectionFromFile = new PrivateFontCollection(); foreach (var file in Directory.GetFiles(@"C:\Window

我需要向
PrivateFontCollection
添加一组字体。 出于某种原因,应使用
AddMemoryFont
函数完成此任务

    var fontCollectionFromMemory = new PrivateFontCollection();
    var fontCollectionFromFile = new PrivateFontCollection();
    foreach (var file in Directory.GetFiles(@"C:\Windows\Fonts", "*.ttf"))
    {
        using (var stream = File.OpenRead(file))
        {
            var fontData = new byte[stream.Length];
            stream.Read(fontData, 0, fontData.Length);
            var fontDataPtr = Marshal.AllocCoTaskMem(fontData.Length);
            try
            {
                Marshal.Copy(fontData, 0, fontDataPtr, fontData.Length);
                fontCollectionFromMemory.AddMemoryFont(fontDataPtr, fontData.Length);
                Thread.Sleep(100);
            }
            finally
            {
                Marshal.FreeCoTaskMem(fontDataPtr);
            }
        }

        // fontCollectionFromFile.AddFontFile(file);
    }
    Console.WriteLine($"PrivateFontCollection's size(filled via AddMemoryFont): {fontCollectionFromMemory.Families.Length}");
    Console.WriteLine($"PrivateFontCollection's size(filled via AddFontFile): {fontCollectionFromFile.Families.Length}");
运行上述代码后,我得到以下输出:

PrivateFontCollection's size(filled via AddMemoryFont): 34
PrivateFontCollection's size(filled via AddFontFile): 0
这个结果非常令人困惑

如果我取消注释以下行:

fontCollectionFromFile.AddFontFile(file);
然后我得到:

PrivateFontCollection's size(filled via AddMemoryFont): 166
PrivateFontCollection's size(filled via AddFontFile): 198
这一结果也令人困惑

如何解释这些结果? 使用PrivateFontCollection.AddMemoryFont的正确方法是什么

环境:
  • Windows 10主页

  • .Net核心2.2.106

  • 系统图.通用4.7.0


谷歌最热门的产品有一个非常讨厌的bug,在这段代码中复制。在无法再使用字体之前,不得调用Marshal.FreeCoTaskMem()。实际上,这意味着在程序调用PrivateFontCollection.Dispose()之前不应该调用它。因为从来没有人这样做过,实际上这意味着你永远不应该打电话给FreeCoTaskMem()。谢谢!我会考虑的。使用注释的Marshal.FreeCoTaskMem()测试了我的示例。结果是一样的。谷歌最热门的有一个非常讨厌的bug,在这段代码中复制。在无法再使用字体之前,不得调用Marshal.FreeCoTaskMem()。实际上,这意味着在程序调用PrivateFontCollection.Dispose()之前不应该调用它。因为从来没有人这样做过,实际上这意味着你永远不应该打电话给FreeCoTaskMem()。谢谢!我会考虑的。使用注释的Marshal.FreeCoTaskMem()测试了我的示例。结果是一样的。