我们创建了大量的字体供短时间使用。字体嵌入在文档中。我想删除字体文件,如果不再使用。我们该怎么做呢?以下简化的代码不起作用:
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之前。这适用于Windows7,但在Windows8 .NET中,在释放第一个FontFamily之后,使用了错误的字体文件。因为每个文档都可以包含其他字体,所以我们需要大量的字体,并且不能包含对所有字体的引用。
发布于 2014-10-31 18:40:49
查看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);https://stackoverflow.com/questions/26671026
复制相似问题