To embed a resource:
Further, if the resource is placed in a project folder, the name of the folder is added into the resource name. For example, if the embeded resource XXX.xslt, exampled above, is placed in a project folder "Resources" then the resource name when retrieving it is now MyNamespace.Resources.XXX.xslt.
To retrieve a resource thus embedded use the method GetManifestResourceStream on the assembly object. For example to retrieve the embedded resource MyNamespace.Resources.XXX.xslt from the executing assembly:
To retrieve a binary embedded resource:
- Add it to the project
- Change the build action to "Embedded Resource"
Further, if the resource is placed in a project folder, the name of the folder is added into the resource name. For example, if the embeded resource XXX.xslt, exampled above, is placed in a project folder "Resources" then the resource name when retrieving it is now MyNamespace.Resources.XXX.xslt.
To retrieve a resource thus embedded use the method GetManifestResourceStream on the assembly object. For example to retrieve the embedded resource MyNamespace.Resources.XXX.xslt from the executing assembly:
private string RetrieveEmbeddedStringResource(string resourceName)
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream fileStream = myAssembly.GetManifestResourceStream(resourceName);
string text = "";
if (fileStream != null)
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
text = streamReader.ReadToEnd();
}
}
return text;
}
and to call it:
string xslt = RetrieveEmbeddedStringResource(
"ViewNUnitTestResults.Resources.NUnitTestResultsToHtml.xsl");
In this case the namespace is ViewNUnitTestResults, the resource is NUnitTestResultsToHtml.xsl which is stored under the project subdirectory Resources.
To retrieve a binary embedded resource:
private byte[] RetrieveByteArrayEmbeddedResource(string resourceName)
{
byte[] bytes = new byte[0];
Assembly myAssembly = Assembly.GetExecutingAssembly();
bool resFound = myAssembly.GetManifestResourceNames().Contains(resourceName);
if (!resFound)
throw new ArgumentException("Could not find the embeded resource \'" +
resourceName + "\'");
using (Stream stream = myAssembly.GetManifestResourceStream(resourceName))
{
bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
}
return bytes;
}
and it is called like this
byte[] bytes = RetrieveByteArrayEmbeddedResource("XXXTests.Something.bin");
No comments:
Post a Comment