[英]Read text file resource from .net library
I have a library that is used in a wpf mef application. 我有一个在wpf mef应用程序中使用的库。 Included in this library are a number of files.
该库中包含许多文件。 One of them is app.js.
其中之一是app.js。
How do I read app.js from the library as a string. 如何从库中以字符串形式读取app.js。
PS: From an earlier code, I can access/create a bitmap image using the code below: PS:从较早的代码,我可以使用以下代码访问/创建位图图像:
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? 生成Uri后,如何获得作为系统流的流的访问权限?
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; Assembly.GetExecutingAssembly()
)上起作用, 而不在调用程序集或任何其他程序集上起作用; 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")
resourceName
应该仅是文件名 (例如,如果文件保存在resources/myRes.bin
,则调用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 . 您可以使用Assembly.GetManifestResourceStream在程序集中打开资源流。 If you are unsure of the name of the resource, you can enumerate the resources names with Assembly.GetManifestResourceNames .
如果不确定资源名称,则可以使用Assembly.GetManifestResourceNames枚举资源名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.