I have a library that is used in a wpf mef application. Included in this library are a number of files. One of them is app.js.
How do I read app.js from the library as a string.
PS: From an earlier code, I can access/create a bitmap image using the code below:
private readonly BitmapImage _starImageSmall = new BitmapImage(new Uri("pack://application:,,,/MyFirstExtension;component/Star_16x16.png", UriKind.Absolute));
After generating the Uri, how do I get access to the stream as the system stream?
This block of code has never failed me:
private Stream GetEmbeddedResourceStream(string resourceName)
{
Assembly assy = Assembly.GetExecutingAssembly();
string[] res = assy.GetManifestResourceNames();
for (int i = 0; i < res.Length; i++)
{
if (res[i].ToLower().IndexOf(resourceName.ToLower()) != -1)
{
return assy.GetManifestResourceStream(res[i]);
}
}
return Stream.Null;
}
Three things to note with this code block:
Assembly.GetExecutingAssembly()
), not the calling assembly or any other assembly; change it to suit your needs (see below for alternative) resourceName
should be the filename only (eg If your file is saved at resources/myRes.bin
, you call GetEmbeddedResourceStream("myRes.bin")
If, however, you want the code to work on arbitrary assemblies, you can change the code block to:
private Stream GetEmbeddedResourceStream(string resourceName)
{
return GetEmbeddedResourceName(resourceName, Assembly.GetExecutingAssembly());
}
private Stream GetEmbeddedResourceStream(string resourceName, Assembly assembly)
{
string[] res = assembly.GetManifestResourceNames();
for (int i = 0; i < res.Length; i++)
{
if (res[i].ToLower().IndexOf(resourceName.ToLower()) != -1)
{
return assembly.GetManifestResourceStream(res[i]);
}
}
return Stream.Null;
}
You can open resource streams in an assembly with Assembly.GetManifestResourceStream . If you are unsure of the name of the resource, you can enumerate the resources names with Assembly.GetManifestResourceNames .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.