Thursday, September 6, 2012

How to access Manifest (Embedded) resource from an Assembly in WinRT application.


In this blog post, I am going to demonstrate on how to access a simple XML file embedded in the WinRT assembly.

One of the easier way to retrieve an assembly in .Net application is by using below method.
// This will return the assembly whose code is currently executing.
Assembly.GetExecutingAssembly();

Alternate one is to use Type object of the classes present in the assembly.
Assembly assembly = typeof(DemoClass).GetType().Assembly;

From the assembly object we can retrieve the manifest resource stream (embedded file) using GetManifestResourceStream() method. All we need is to pass the name of the embedded resource. The name of the embedded resource is the combination of root namespace, folder path and the file name.

For example consider the root namespace of a demo application to be MyApp and the XML file (Embedded.xml) is available under Resources folder of the assembly. Then the name of the embedded resource is “MyApp.Resources.Embedded.xml”.

Sample code snippet for .Net
Assembly assembly = Assembly.GetExecutingAssembly();
Or
Assembly assembly = typeof(DemoClass).GetType().Assembly;

Stream xmlStream = assembly.GetManifestResourceStream("MyApp.Resources.Embedded.xml");

In WinRT, Both GetExecutingAssembly() and GetType().Assembly are not available, instead you can retrieve the assembly object from the classes declared in the assembly by means of using TypeInfo object. Now the remaining part to access the manifest resource is same as in .Net application. Please find the code snippet from below.

Sample code snippet for WinRT
Assembly assembly = typeof(DemoClass).GetTypeInfo().Assembly;
Stream xmlStream = assembly.GetManifestResourceStream("MyApp.Resources.Embedded.xml");

Please find the demo application from below link


In this application, embedded XML file is retrieved and its contents are displayed in a text box.

No comments:

Post a Comment