Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an embedded resource from a shared project

I'm working on a Xamarin Forms app which has two projects, an Android App and an iOS app. All the other code is stored in shared projects.

Solution looks like this:

  • MyApp.Android (Android project), references MyApp.Base
  • MyApp.iOS (iOS project), references MyApp.Base
  • MyApp.Base (Shared project)

I am using the following code to read an SVG image from the shared project:

using (var stream = GetType().Assembly.GetManifestResourceStream("MyApp.Base.image.svg"))
{
    // do work here...
}

This works perfectly when the image is in the Android or iOS project, but I want the image to be shared so I put it in the shared project.

GetType().Assembly return MyApp.Android, thus it cannot find the image. I suppose I'm overlooking something but I haven't been able to find a solution.

Can anyone point me in the right direction? Thanks!

like image 423
Jasper Avatar asked Nov 15 '25 10:11

Jasper


1 Answers

You are using the Shared Project NOT the PCL or .Net Standard library. So, all of your Shared Project contents will get merged into the Platform specific project when you Compile them. That means - even if you Embed your resource in your MyApp.Base that will get merged into .iOS/.Droid project. I suggest you to learn more about Shared Project vs PCL or .Net Standard library. Below code; I did't tested but this is the direction that you should follow:

#if __IOS__
    var resourcePrefix = "MyApp.iOS.";
#endif
#if __ANDROID__
    var resourcePrefix = "MyApp.Android.";
#endif

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(SharedPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream
(resourcePrefix + "image.svg");

For more information please look into this page : https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/files?tabs=macos#embedding-in-shared-projects

like image 173
Nirmal Subedi Avatar answered Nov 17 '25 06:11

Nirmal Subedi