I added an XML file as an embedded resource in my class library by using the accessing the project properties in Visual Studio and then Resources | Add Resource | Add Existing File…
I’ve tried to access the file using the following code, but I keep getting a null reference returned. Anyone have any ideas?
var path = Server.MapPath("~/bin/MyAssembly.dll");
var assembly = Assembly.LoadFile(path);
var stream = assembly.GetManifestResourceStream("MyNamespace.filename.xml");
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I find it much easier to use the “Resources” tab of the project’s properties dialog in Visual Studio. Then you have a generated strongly typed reference to your resource through:
Properties.Resources.Filename
Method 2
The MSDN page for GetManifestResourceStream makes this note:
This method returns a null reference
(Nothing in Visual Basic) if a private
resource in another assembly is
accessed and the caller does not have
ReflectionPermission with the
ReflectionPermissionFlag.MemberAccess
flag.
Have you marked the resource as “public” in your assembly?
Method 3
I found that this article explains nicely how to set this up: http://www.devx.com/dotnet/Article/10831/1954
One thing that may have helped in this case is using a different method for determining the location of the embedded resource.
- GetEntryAssembly: Use this method to reference the executable file that was run to start the current process. The entry assembly is set for Windows forms applications, but for most other applications (for example, web projects), GetEntryAssembly returns ‘nothing’ (or null, in C#).
- GetExecutingAssembly: Use this method to reference the same assembly that the executing code is in.
- GetCallingAssembly: Use this method to reference the assembly containing the code that called the current method. This method is useful if you write generic code to read embedded resources that is inside a shared assembly where the embedded resource is in the calling assembly.
I personally prefer this method over using the “Resources” tab because it allows me to use other tools to add resources to the project for inclusion on compilation. I don’t have to use the GUI with this tool
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0