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?
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.