views:

711

answers:

2

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");
+2  A: 

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?

Matt Hamilton
I have indeed marked it as public in the assembly. Still a null reference.
Kevin Babcock
Perhaps it's something to do with the "Build Action" setting for that file. Have you tried changing it to different values (eg Embedded Resource vs Content)?
Matt Hamilton
I never set the build action for the file. I only imported the file into a .resx file and was having trouble extracting its contents. Getting rid of the .resx and marking the Build Action as "Embedded Resource" allowed me to access it using the code above. Thanks very much for the tip!
Kevin Babcock
+3  A: 

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
Shawn Miller