Ylvin Pérez Ylvin Pérez - 3 months ago 20
C# Question

Why packing an URI for an image in a WPF project doesn't work if the Build Action property of the image is Content

I'm trying to use an image file in a WPF project implementing Pack URI. According to the book Head First C#, changing the Build Action property of the image to Content is a good practice. Following this guide for an image as Content I could not make it work, nevertheless, changing the image Build Action property to Resource makes it work without a problem. Here is my method code:

public static BitmapImage CreateImageFromAssets(string imageFilename)
{
try
{
Uri uri =
new Uri("pack://application:,,,/Assets/" +
imageFilename, UriKind.Absolute);
return new BitmapImage(uri);
}
catch (IOException)
{
return new BitmapImage();
}
}


I tried using other options like:

Uri uri =
new Uri("pack://application:,,,/BeesOnAStarryNight;component/Assets/"
+ imageFilename, UriKind.RelativeOrAbsolute);
Uri uri =
new Uri("pack://application:,,,/BeesOnAStarryNight;component/Assets/"
+ imageFilename, UriKind.Absolute);


The name of the image file is "Bee1.png". This is the error I got:


An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationCore.dll


I tried without the try catch and got this:


An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll

Additional information: Could not find a part of the path 'C:\Users\myuser\TRAINING\DEV\Assets\Bee1.png'.


Don't know why I got an incomplete path to the solution folder. It is several folders in after /DEV.

Want to know why it only works if the image has a Build Action property of Resource? and Is it really a good practice to use it as Content instead?

Answer

Your URI is a Resource File Pack URI, and it is sufficient to create it without specifying the UriKind, like

var uri = new Uri("pack://application:,,,/Assets/" + imageFilename);

As the name "Resource File Pack URI" implies, the image file must be a resource file, i.e. its Build Action must be Resource.