How to read a resource file within a Portable Class Library?

后端 未结 8 1607
夕颜
夕颜 2020-12-05 03:26

I have a Portable Library which I am using for a Windows Phone application. In that same Portable Library, I have a couple of content files (Build Action = Cont

相关标签:
8条回答
  • 2020-12-05 03:49

    First of all, retrieve your assembly like this (DataLoader being a class in your PCL assembly) :

    var assembly = typeof(DataLoader).GetTypeInfo().Assembly;
    

    Add your file to portable resource and set build action to Embedded Resource.

    Then you can retrieve your ressource like this :

    string resourceNam= "to be filled";
    var assembly = typeof(DataLoader).GetTypeInfo().Assembly;
    var compressedStream = assembly.GetManifestResourceStream(resourceName));
    

    For example if I have a file logo.png in a folder "Assets/Logos" in an assembly "TvShowTracker.Helpers" I will use this code :

    string resourceNam= "TvShowTracker.Helpers.Assets.Logos.logo.png";
    var assembly = typeof(DataLoader).GetTypeInfo().Assembly;
    var compressedStream = assembly.GetManifestResourceStream(resourceName));
    

    Happy coding :)

    0 讨论(0)
  • 2020-12-05 04:00

    Your path is wrong. You're using slashes, but in the embedded manifest resource names slashes were converted to periods during the build. Also depending on your PCL targeted platforms, you may not even be able to call Assembly.GetExecutingAssembly().

    Here is what you can do:

    var assembly = typeof(AnyTypeInYourAssembly).GetTypeInfo().Assembly;
    
    // Use this help aid to figure out what the actual manifest resource name is.
    string[] resources = assembly.GetManifestResourceNames();
    
    // Once you figure out the name, pass it in as the argument here.
    Stream stream = assembly.GetManifestResourceStream("Some.Path.AndFileName.Ext");
    
    0 讨论(0)
提交回复
热议问题