After looking at the code of the AddFontFile method:
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); }
we see that the font is registered 2 times. First in GDI + and on the last line in GDI32. This is different from the AddMemoryFont method. In the Dispose method, it is not registered in GDI +. This leads to a leak in GDI32.
To compensate for this, you can call the following:
[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);
source share