0

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?

Community
  • 1
  • 1
  • 1
    *"Build Action property of the image to Content is a good practice"* - I'd like to read about it. Most of programmers (including me) are fine with `Resource`, [proof](http://stackoverflow.com/q/347614/1997232) (350 vs 120). – Sinatr Sep 01 '16 at 15:23
  • I'd say the opposite, it's bad practice. Setting `Resource` would be good practice. – Clemens Sep 01 '16 at 15:42
  • Thanks for the clarification guys. –  Sep 01 '16 at 16:05

1 Answers1

2

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.

Clemens
  • 123,504
  • 12
  • 155
  • 268