Search code examples
c#wpfimageresourcesxamlparseexception

Can't open an image in WPF app


In my application I want to display some pictures (I need to have them stored in a list). I have problem with opening them. Firstly, I made a directory Images (using VS). Next I loaded pictures to this folder (also in VS). I wanted to open one of them like here: http://msdn.microsoft.com/en-us/library/aa970062.aspx

Stream imageStreamSource = new FileStream("Images\bulbOff.png", FileMode.Open, FileAccess.Read, FileShare.Read);
PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];

And then while trying to run the program, I got:

XamlParseException

with hardly any information. For sure the first line is causing the problem, because the problem disappears only when I delete it.

I tried to do it also like:

Uri myUri = new Uri("Images\bulbOff.png", UriKind.RelativeOrAbsolute);
PngBitmapDecoder decoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource2 = decoder2.Frames[0];

with the same result. I also tried to copy the image to main folder of app (in SolutionView). When I tried to get "\bulbOff.png" the result was the same. When I tried to get "bulbOff.png" I got

XamlParseException

again, but with some info - there were hints that path could be wrong.


Solution

  • If you want to provide a BitmapImage...

    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.UriSource = new Uri(@"..\Images\DocumentAccess_16x16.png", UriKind.Relative);
    image.EndInit();
    

    ...where Images is a folder within your project.