In .Net when you don’t want to relay for a file on physical location, then it is very good option to take an advantage of Embedded resources.
Using embedded resources you can add any file type in the assembly/DLL/EXE when they get compiled. And whenever you want to use it, load it from the assembly, the files get stored in the metadata of Assembly.
Here is an example of how to use Embedded Resources.
1.
Open Microsoft Visual Studio and create new project for C# Windows Application, here I have created Windows Application named “EmbeddedTest”, even you can use “Class Library” 2.
To add a file in the project Right click on the project name in Solution Explorer, select “Add” >> “Existing Item…”
3.
Now we have added a file to the project, so it doesn’t mean that it will automatically embedded in the Assembly, for that we need to change the files “Build Action” property to “Embedded Resource”, and compiler will include this file in metatdata. Here I have added Image file(dog.jpg), you can add one or more any kind of files
4.
Now use the following code in Form1_Load method to list all the Embedded Resources available in the Assembly
private void Form1_Load(object sender, EventArgs e){Assembly a = Assembly.GetExecutingAssembly(); string[] resources = a.GetManifestResourceNames(); foreach (string resourceName in resources){listBox1.Items.Add(resourceName);}}
5.
The following code is used to get the resource from the Manifest of the Assembly when user clicks on the listBox1
private void listBox1_SelectedIndexChanged(object sender, EventArgs e){if (listBox1.SelectedIndex == -1)return; string selectedResourceName = listBox1.SelectedItem.ToString(); Assembly a = Assembly.GetExecutingAssembly(); Stream stream = a.GetManifestResourceStream(selectedResourceName); if (stream != null){pictureBox1.Image = null;try{Bitmap bmp = Bitmap.FromStream(stream) as Bitmap; pictureBox1.Image = bmp;}catch (Exception ex){MessageBox.Show("Selected item is not Image");} }}
In Step 5 the we first got the Stream by using GetManifestResourceStream() and then after we load it in to Bitmap object, if in between error occurs when the Resource is not type of Bitmap an Exception is thrown and error message is displayed.
Download Full Source Code
Download Project EmbeddedTest.zip (349.79 KB)
Download Project With Example of using Class Library (866.59 KB)
