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?