在运行时枚举.NET程序集资源 [英] Enumerating .NET assembly resources at runtime

查看:199
本文介绍了在运行时枚举.NET程序集资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在使用的资源内容的生成操作建在它的图像文件资源组件。这使得这些文件可以访问使用这些URI。但是我找不到列举这些资源的方式。
如果我设置构建动作的嵌入的资源的就有可能枚举文件具有以下code:

I have a resource assembly with image files in it that are built using Resource or Content build action. This makes these files accessible using the Uris. However I cannot find the way to enumerate such resources.
If I set the build action to Embedded Resource it becomes possible to enumerate the files with the following code:

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

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

but it in turn makes these files inaccessible using Uris.

现在的问题是 - 如何枚举被编译的资源无论是的资源内容的建设的行动

The question is - how to enumerate resources that are compiled with either Resource or Content build action?

注:正如托马斯·莱维斯克指出,可以通过利用AssemblyAssociatedContentFileAttribute列举这样的资源,但它似乎只对WPF应用程序组件,而不是为类库的。所以,问题仍然是开放的。

NOTE: As Thomas Levesque pointed out it is possible to enumerate such resources by leveraging the AssemblyAssociatedContentFileAttribute, but it seems to only work for WPF Application assemblies and not for class library ones. So the question is still open.

推荐答案

您可以枚举<一href="http://msdn.microsoft.com/en-us/library/system.windows.resources.assemblyassociatedcontentfileattribute.aspx"><$c$c>AssemblyAssociatedContentFile在装配属性定义的:

You can enumerate the AssemblyAssociatedContentFile attributes defined on the assembly :

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

您还可以查看此页面一种方式枚举BAML资源。

You can also check this page for a way to enumerate BAML resources.

更新:其实上述解决方案仅适用于内容的文件。该方法初级讲座返回所有资源名(包括BAML资源,图像等):

UPDATE : actually the solution above works only for Content files. The method belows returns all resource names (including BAML resources, images, etc) :

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

这篇关于在运行时枚举.NET程序集资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆