Working with embedded resources in Project's assembly

Embedding resources in project’s assembly can be very useful for static data that exists in your project, such as images, some static files etc.

For this purpose, .NET Framework is equipped with Assembly class which is derived from the System.Reflection.

Using Assembly class and its methods, we can easily access and work with the embedded resources.

Here is one simple example to demonstrate the ability of embedding resources in one ASP.NET Application.

 

- I have three images inside images folder:

assembly_images[1]

- Selecting the images

assembly_images_s[1]

- Then go to Properties. In Build Action chose Embedded Resources (see the image bellow)

assembly_images_embed[1]

 

After the next Build you do, the images will be embedded as assembly resources in your project’s assembly.

Next thing is how to access the resources. As I’ve mentioned previously, you can use the Assembly class. Here is one complete example where I am using several methods for accessing the resources:

            Assembly asm = Assembly.GetExecutingAssembly();
            
            //will loop tru all assembly files
            foreach (string assembly in asm.GetManifestResourceNames())
            {
                Response.Write(assembly);
            }

            //will load all the resource names in the string array
            string[] assemblies = asm.GetManifestResourceNames();
            
            //will load specified assembly file to the Stream
            System.IO.Stream strm = asm.GetManifestResourceStream("Blogs.images.image1.JPG");

- Assembly.GetExecutingAssembly() – as the method name says, using this method we will get the assembly that contains the current code which is executing.

- Assembly.GetManifestResourceNames() – this method will return the names of all the resources in this assembly, it will return string[]

- Assembly.GetManifestResourceStream(“manifestResource”) – this method will load the specified manifest resource from the current assembly into a Stream.

You should know:

- You see, when referring to the image1.JPG in the GetManigestResourceStream(“Blogs.images.image1.JPG”) – we are using periods (.) in the hierarchy tree (instead of /).

- The resource path has the following form: [Namespace].[folder].[filename].[fileExstension]

- Don’t forget the System.Reflection directive

- Embedded resource path is key-sensitive, so Blogs.images.image1.JPG is not the same as Blogs.images.image1.jpg – be careful with that!

 

I hope this was helpful!

3 Comments

Comments have been disabled for this content.