C# 从.net库读取文本文件资源

C# 从.net库读取文本文件资源,c#,.net,mef,C#,.net,Mef,我有一个用于wpf mef应用程序的库。此库中包含许多文件。其中之一是app.js 如何将库中的app.js作为字符串读取 PS:根据前面的代码,我可以使用以下代码访问/创建位图图像: private readonly BitmapImage _starImageSmall = new BitmapImage(new Uri("pack://application:,,,/MyFirstExtension;component/Star_16x16.png", UriKind.Absolute))

我有一个用于wpf mef应用程序的库。此库中包含许多文件。其中之一是app.js

如何将库中的app.js作为字符串读取

PS:根据前面的代码,我可以使用以下代码访问/创建位图图像:

private readonly BitmapImage _starImageSmall = new BitmapImage(new Uri("pack://application:,,,/MyFirstExtension;component/Star_16x16.png", UriKind.Absolute));

生成Uri后,如何获得作为系统流的流的访问权限?

您可以使用打开程序集中的资源流。如果不确定资源的名称,可以使用枚举资源名称。

这段代码从未让我失望过:

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;
}

您提到它是一个MEF应用程序。这是否意味着您希望通过MEF导出使这些资源文件可用?目前,我在下面的回答中忽略了MEF,因为不清楚它是如何(或应该)参与进来的。@WimCoenen没有。我实际上在为WebMatrix编写扩展,因为它使用MEF,我认为有必要提及它。科尔和你的解决方案都给了我我所需要的。效果很好。函数末尾的return语句有什么原因吗?@ritcoder这样编译器就不会抛出一个fit,以防文件不存在!我注意到,在我的库项目中,文件需要是“嵌入式资源”。我试过“内容”和“资源”,但都没用。
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;
}