GetManifestResourceStream returns NULL

前端 未结 13 2666
走了就别回头了
走了就别回头了 2020-11-28 05:41

This is a C# .NET 4.0 application:

I\'m embedding a text file as a resource and then trying to display it in a dialog box:

    var assembly = Assembl         


        
13条回答
  •  执念已碎
    2020-11-28 06:04

    Although OP got GetManifestResourceStream returning NULL from resources in the same Assembly, some Answers suggested that when Resources are in another Project or Assembly they cannot be retrieved, and are a fair cause of GetManifestResourceStream returning NULL.

    This is not true, at least since 2011; as I pointed in some comments elsewhere, Assembly.LoadFrom() or typeof do the trick and as a result you can access resources that are in another project.

    I have a moderately complex example here to illustrate; this is my test setup:

    Path to another project:

    Captured here:

     var sharedXMLResource =
                    "D:\\My Documents\\Consultório Impressos\\DB Pacientes\\Teste\\TestesVariados\\WinFormFramework\\Read_Embedded_XML_File_CS\\bin\\Debug\\Read_Embedded_XML_File_CS.exe";
    

    And on Form1.cs from WinFormFramework I specify with

    Namespace.Folder.Resource

    like that:

    StreamReader reader = 
                    new StreamReader(Assembly.LoadFrom(sharedXMLResource).GetManifestResourceStream("Read_Embedded_XML_File_CS.SharedResources.ContactList.xml") ?? throw new InvalidOperationException());
    

    And the result displayed at textbox:

    I spent several hours to get it right; for that, I had to use a lot these at Immediate Window:

    Environment.CurrentDirectory
    AppDomain.CurrentDomain.BaseDirectory
    System.Reflection.Assembly.GetExecutingAssembly().Location
    System.Reflection.Assembly.GetAssembly(typeof(WinFormFramework.Program)).Location
    

    Hope it helps someone

提交回复
热议问题