Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

c# - GetManifestResourceStream returns NULL

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 = Assembly.GetExecutingAssembly();
    var resourceName = "MyProj.Help.txt";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                string result = reader.ReadToEnd();
                System.Windows.Forms.MessageBox.Show(result, "MyProj", MessageBoxButtons.OK);
            }
        }

The solution is MyProjSolution and the executable is MyProj.exe. Help.txt is an embedded resource. However, the stream is null. I've tried MyProjSolution.Help.txt and MyProjSolution.MyProj.Help.txt but nothing seems to work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can check that the resources are correctly embedded by using

//From the assembly where this code lives!
this.GetType().Assembly.GetManifestResourceNames()

//or from the entry point to the application - there is a difference!
Assembly.GetExecutingAssembly().GetManifestResourceNames()

when debugging. This will list all the (fully qualified) names of all resources embedded in the assembly your code is written in.

See Assembly.GetManifestResourceNames() on MSDN.

Simply copy the relevant name, and use that instead of whatever you have defined in the variable 'resourceName'.

Notes - the resource name is case sensitive, and if you have incorrectly embedded the resource file, it will not show up in the list returned by the call to GetManifestResourceNames(). Also - make sure you are reading the resource from the correct assembly (if multiple assemblies are used) - it's all too easy to get the resources from the currently executing assembly rather than from a referenced assembly.

EDIT - .NET Core
Please see this SO post for details on how to embed using .NET Core.

Retrieving the manifest info looks to be similar - just use this.GetType().GetTypeInfo().Assembly.GetManifestResourceNames() to get the a manifest from the assembly where the code is executing.

I haven't figured out how to do the equivalent of Assembly.GetExecutingAssembly() in .NET Core yet! if anyone knows - please let me know and I will update this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...