JamesPD
JamesPD

Reputation: 620

C# - Loading image from file resource in different assembly

C# - Loading image from file resource in different assembly

I have a PNG image file which is stored in a project called SomeProject and displayed various times using XAML in that same project. In a different assembly, I now wish to access that same image. Previously I was simply specifying a relative path to the actual file which worked fine. However, when I build a release installer, the image files are packed into the SomeProject.DLL.

Is there any easy way I can access the PNG file from another assembly without simply resorting to copying the file locally to the second project? I though it might be possible using 'pack://' but I'm not having much luck.

// SomeOtherProject.SomeClass.cs ...

Image logo = new Image();
BitmapImage logoSource = new BitmapImage();
eChamSource.BeginInit();

// Following line works fine is Visual Studio, but obviously not after installation
// logoSource.UriSource = new Uri(@"..\SomeProject\Resources\Images\logo.png", UriKind.Relative);

logoSource.UriSource = new Uri("pack://application:,,,/SomeProject;component/Resources/Images/logo.png");
logoSource.EndInit();

logo.Width = 100; logo.Height = 100;
logo.Source = logoSource;

Any advice would be good.

Upvotes: 0

Views: 5256

Answers (2)

Flot2011
Flot2011

Reputation: 4671

Try to load your other assembly as followed:

Application.LoadComponent(new Uri(@"AnotherAssembly;;;component\AnotherResourceFilePath/logo.png", UriKind.Relative)));

LoadComponent function returns an object. It is up to you to cast it to the appropriate type.

Upvotes: 1

coder
coder

Reputation: 13248

If the images you wish to use as Content is in another assembly, you must copy them to the main projects directory.

You can use a Build event to do this:

Right click project that contains images -> Properties -> Buil Events -> edit post build to copy images to main project directory.

Then you have to use it as

pack://application:,,,/ContentFile.xaml

(Or)

If you need it in subfolder

pack://application:,,,/Subfolder/ContentFile.xaml

Have a look at this hfor more information http://msdn.microsoft.com/en-us/library/aa970069.aspx

Upvotes: 1

Related Questions