8

我们为短期使用创建了大量字体。字体嵌入在文档中。如果不再使用,我想删除字体文件。我们应该怎么做?以下简化代码不起作用:

PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile(fontFile);
FontFamily family = pfc.Families[0];
Console.WriteLine(family.GetName(0));

family.Dispose();
pfc.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
File.Delete(fontFile);

由于文件被锁定,文件删除失败。我还能做些什么来释放文件锁?

PS:在我们使用 AddMemoryFont 之前。这适用于 Windows 7。但在 Windows 8 .NET 中,在处置第一个 FontFamily 后使用错误的字体文件。因为每个 Document 都可以包含其他字体,所以我们需要大量的字体并且不能包含对所有字体的引用。

4

1 回答 1

14

查看 AddFontFile 方法的代码后:

public void AddFontFile(string filename)
{
    IntSecurity.DemandReadFileIO(filename);
    int num = SafeNativeMethods.Gdip.GdipPrivateAddFontFile(new HandleRef(this, this.nativeFontCollection), filename);
    if (num != 0)
    {
        throw SafeNativeMethods.Gdip.StatusException(num);
    }
    SafeNativeMethods.AddFontFile(filename);
}

我们看到字体注册了 2 次。首先在 GDI+ 中,在 GDI32 中的最后一行。这与 AddMemoryFont 方法不同。在 Dispose 方法中,它仅在 GDI+ 中未注册。这会导致 GDI32 中的泄漏。

为了弥补这一点,您可以调用以下命令:

[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int RemoveFontResourceEx(string lpszFilename, int fl, IntPtr pdv);

pfc.AddFontFile(fontFile);
RemoveFontResourceEx(fontFile, 16, IntPtr.Zero);
于 2014-10-31T10:40:48.563 回答