9
votes

I don't know exactly if it is a bug but i am getting all the time runtime IOException error saying Cannot locate resource.

I am loading some images in my app (c#, WPF) in canvas background depends on database state. The problem is, that i cannot load LAST (alphabeting sorted) file. I have for example 15 images in folder. I can load 14 first without problems. But the last one all the time throw exception.

I am 100% sure, that i HAVE the image in the folder (see !image-printscreen below). And how i wrote. 14 first i can load without any problem, only the last one throw exception.

Is it a bug in WPF-c# or am I doing something wrong?

code what is throwing exception:

canvas_status.Background = new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), @"Images\" + statusName + ".png")));

canvas_name.Background = new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), @"Images\" + statusName + bulheadName + ".png")));

error:

IOException was unhalded
Cannot locate resource 'view/images/panel_uzavreno_d.png'.

image (for higher resolution click on image right mouse button and click on SHOW IMAGE or something like that):

printscreen

2
thats not the problem, that is "newer" version (i found on internet, that this will solve the problem, but it doesnt). When i have it without the "view" folder, it doesnt work as well and it throw same exception :(piggy
@piggy please don't use screenshots from services other than Imgur because they tend to get deleted or blocked which will render your question useless for future visitors with the same problem.Nasreddine
ah ok :]. sorry, it is right now on imgur (thank you for edit)piggy
Are all your images set to Resource and Do not copy?evanb
it is added throught -> add existing item (not in resources but in solution explorer)piggy

2 Answers

36
votes

I've had a similar issue: IOException, cannot locate a png resource which indeed existed in the assembly.

I found the solution by explicitly specifying the assembly name, even though the caller was in the same assembly as the resource.

Here's how it looks with a Pack URI syntax:

pack://application:,,,/MyAssemblyName;component/MyResourcesFolder/MyImage.png

(For more about Pack URIs see http://msdn.microsoft.com/en-us/library/aa970069.aspx)

Edit: One more thing I had to do after specifying the assembly name was to Clean the project. The problem returns after build but was resolved after cleaning the intermediate products. This is definitely a bug in Visual Studio.

22
votes

You need to set the build action of the image to the type 'Resource'.

Right-mouse click on the file >> Properties >> set 'Build Action' to 'Resource'