An embedded resource is one that is embedded inside the
application's code. Thus, when the application is compiled, this resource gets
stored in the assembly that is generated after the compilation of the
application's code. Let us create a text resource file called TextFile.txt and
make the same an embedded resource by selecting the properties of the same file
and then setting the Build Action in the item properties to "Embedded
Resource." This means the resource will be embedded directly into the current
assembly along with the code. Further, let the resource file that has just
been created contain a text message.
The following code snippet shows how we can retrieve the
content of the resource as a string from the current executing assembly.
Listing 6
public string GetResourceFromAssembly(string resourceName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
TextReader txtReader = new
StreamReader(assembly.GetManifestResourceStream(resourceName));
string str = txtReader.ReadToEnd();
txtReader.Close();
return str;
}
The above method accepts the fully qualified path to the
resource as a parameter and returns the resource as a string from the current
executing assembly. Invoke the above method as shown below.
Listing 7
Response.Write(GetResourceFromAssembly("Test.TextFile.txt"));
The GetResourceFromAssembly method would return the resource
value from the specified resource file.
It is also possible to list all the embedded resources in
the assembly as shown in the section below. The following method shows how we
can display the names of all the embedded resources in the current executing
assembly.
Listing 8
public string GetResourceNamesFromAssembly()
{
Assembly assembly = Assembly.GetExecutingAssembly();
string [] resourceNames = assembly.GetManifestResourceNames();
StringBuilder stringBuilder = new StringBuilder();
foreach(string str in resourceNames)
{
stringBuilder.Append(str);
stringBuilder.Append("<BR>");
}
return stringBuilder.ToString();
}
The above method would return all the resource names from
the current executing assembly. Invoke the above method as shown in the listing
below.
Listing 9
Response.Write(GetResourceNamesFromAssembly());