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.
Open Solution Explorer add files you want to embed. Right click on the files then click on Properties . In Properties window and change Build Action to Embedded Resource . After that you should write the embedded resources to file in order to be able to run it.
Embedded resource has no predefined structure: it is just a named blob of bytes. So called “. resx” file is a special kind of embedded resource. It is a string -to-object dictionary that maps a name to an object. The object may be a string , an image, an icon, or a blob of bytes.
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");
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With