在运行时枚举.NET程序集资源

时间:2010-03-25 16:34:12

标签: .net wpf resources

我有一个包含图像文件的资源程序集,它使用 Resource Content 构建操作构建。这使得可以使用Uris访问这些文件。但是我找不到列举这些资源的方法 如果我将构建操作设置为嵌入式资源,则可以使用以下代码枚举文件:

string[] resources = Assembly.GetExecutingAssembly().GetManifestResourceNames();

但它反过来使用Uris无法访问这些文件。

问题是 - 如何枚举使用资源内容构建操作编译的资源?

注意:正如Thomas Levesque指出的那样,可以通过利用AssemblyAssociatedContentFileAttribute来枚举这些资源,但它似乎只适用于WPF应用程序集,而不适用于类库。所以问题仍然存在。

1 个答案:

答案 0 :(得分:27)

您可以枚举程序集中定义的AssemblyAssociatedContentFile属性:

var resourceUris = Assembly.GetEntryAssembly()
                   .GetCustomAttributes(typeof(AssemblyAssociatedContentFileAttribute), true)
                   .Cast<AssemblyAssociatedContentFileAttribute>()
                   .Select(attr => new Uri(attr.RelativeContentFilePath));

您还可以查看this page以了解枚举BAML资源的方法。


更新:实际上上述解决方案仅适用于内容文件。下面的方法返回所有资源名称(包括BAML资源,图像等):

    public static string[] GetResourceNames()
    {
        var asm = Assembly.GetEntryAssembly();
        string resName = asm.GetName().Name + ".g.resources";
        using (var stream = asm.GetManifestResourceStream(resName))
        using (var reader = new System.Resources.ResourceReader(stream))
        {
            return reader.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).ToArray();
        }
    }
相关问题