Skip to content

Fix TypeInitializationException when system has duplicate font names#121

Open
punker76 wants to merge 1 commit intodotnetprojects:masterfrom
punker76:fix/duplicate-font-names
Open

Fix TypeInitializationException when system has duplicate font names#121
punker76 wants to merge 1 commit intodotnetprojects:masterfrom
punker76:fix/duplicate-font-names

Conversation

@punker76
Copy link
Copy Markdown

Description

  • Fix TypeInitializationException / ArgumentException in FontResolver when the system has duplicate font names (e.g. "bundaysans")
  • Replace ToDictionary with GroupBy + ToDictionary to gracefully handle duplicates by keeping the first occurrence

Problem

On systems where Fonts.SystemFontFamilies returns multiple font families with the same name (case-insensitive), the FontResolver constructor crashes with an ArgumentException: An item with the same key has already been added.

Since FontResolver is used in the static constructor of TextStyle, this causes a TypeInitializationException that prevents any SVG with text elements from rendering:

  System.TypeInitializationException: The type initializer for 'SVGImage.SVG.TextStyle' threw an exception.
   ---> System.ArgumentException: An item with the same key has already been added. Key: bundaysans
     at System.Linq.Enumerable.ToDictionary[...]
     at SVGImage.SVG.Utils.FontResolver..ctor(Int32 maxLevenshteinDistance)
     at SVGImage.SVG.TextStyle..cctor()

Solution

Replaced the direct ToDictionary call with GroupBy + ToDictionary, which groups fonts by name first and then picks the first entry per group. This avoids the duplicate key exception while keeping the original lookup behavior intact.

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

Please describe the tests that you ran to verify your changes.

  • .NET Framework, Version 4.0
  • .NET Framework, Version 4.5
  • .NET Framework, Version 4.6
  • .NET Framework, Version 4.7
  • .NET Framework, Version 4.8
  • .NET Core, Version 3.1
  • .NET 6 ~ 8
  • All Included Samples

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works

Fonts.SystemFontFamilies can return multiple entries with the same name,
causing ToDictionary to throw an ArgumentException. Use GroupBy to handle
duplicates by keeping the first occurrence.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant