cs0815
cs0815

Reputation: 17388

How to get resources embedded in another project

Let us say I have a C# class library project, which only contains xml files as embedded resources. I would like to access these resources from another solution project. As the 'class' library contains no classes it is quite hard to obtain the assembly like this:

typeof(ClassName).Assembly ...

to eventually get to the embedded resources. Is there a way to get to the embedded resources without having to hard code any magic strings etc.? Thanks.

PS:

This seems the only way possible at the moment:

var assembly = typeof(FakeClass).Assembly;
var stream = assembly.GetManifestResourceStream("Data.Blas.xml"); 

I have created a 'fake class' in my 'data' assembly.

Upvotes: 30

Views: 26575

Answers (2)

Mike Cheel
Mike Cheel

Reputation: 13106

Here is an approach I find works pretty well when I don't want loose files in the project. It can be applied to any assembly.

In the following example there is a folder in the root of the project called 'MyDocuments' and a file called 'Document.pdf' inside of that. The document is marked as an Embedded resource.

You can access the resource like this, building out the namespace first before calling GetManifestResourceStream():

Assembly assembly = Assembly.GetExecutingAssembly();
string ns = typeof(Program).Namespace;
string name = String.Format("{0}.MyDocuments.Document.pdf", ns);
using (var stream = assembly.GetManifestResourceStream(name))
{
    if (stream == null) return null;
    byte[] buffer = new byte[stream.Length];
    stream.Read(buffer, 0, buffer.Length);
    return buffer;
}

The only issue I have found is when the name space contains numbers after a '.' (e.g. MyDocuments.462). When a namespace is a number the compiler will prepend an underscore (so MyDocuments.462 becomes MyDocuments._462).

Upvotes: 2

Kurubaran
Kurubaran

Reputation: 8902

you can use Assembly.GetManifestResourceStream() to load the xml file from the embedded assembly.

System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("ActivityListItemData.xml"); 

EDIT

You can use Assembly.Load() and load the target assembly and read the resource from there.

Assembly.LoadFrom("Embedded Assembly Path").GetManifestResourceStream("ActivityListItemData.xml");

Upvotes: 21

Related Questions