C# .NET6 referencing embedded .ico file fails in debugging in VS

126 Views Asked by At

I have a valid multi-size .ico image file in the Resource directory of my VS C# .NET6 WPF project. This resource file is marked as Embedded resource to be included in the binary.

I try to explicitly reference it with

Uri iconUri = new Uri("pack://application:,,,/Resources/iconfile.ico");
this.Icon = BitmapFrame.Create(iconUri);

There is no compilation errors in the project. This second line gives a runtime error in VS 2022 debugger: System.IO.IOException: Cannot locate resource 'resources/iconfile.ico'.

Please could you help me understand why this resource component is not visible to the code.

ChatGPT and forum archives didn't produce any explanation for this.

P.S. It doesn't seem to complain about the neighbour .png file (also marked as embedded resource), which I refer in an XAML file directly with a similar URI as a Source for <Image>. Initially I referred to the .ico file also in my XAML to assign it as an Icon in <Window>, but I got the same runtime error for InitialiseComponent(); so I decided to refer to it explicitly in .cs and got the same effect.

I also noticed that my .ico file is PNG-based for the 256x256 size and BMP-based for all other sizes... Can this have anything to do with the issue?

2

There are 2 best solutions below

2
Etienne de Martel On BEST ANSWER

In short, you need to mark your file with the "Resource" build action, not "Embedded resource".

Embedded resources are for manifest resources, that you load with methods like Assembly.GetManifestResourceStream(). It's a different thing.

For WPF to load a resource from a pack URI, it needs to be built with the Resource build action.

1
Infinyte On

Multi sized icon files need to be 16x16, 32x32, 48x48 and 256x256 pixels and require at least one blank pixel around the outer edge of entire image enclosed within. Check to make sure that your icon is not touching one of the outer edges of the grid and that all sizes are using the same format (PNG, BMP, etc.)

Consider running your source images through an online ICO convertor to validate and ensure that the icon in correct.

https://convertio.co/png-ico/