简体   繁体   中英

How can I retrieve an embedded xml resource?

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");

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM