枚举嵌入资源目录中的文件 [英] Enumerating files in an embedded resource directory

查看:63
本文介绍了枚举嵌入资源目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 WPF 中,有没有办法枚举特定嵌入资源目录中的所有文件?也就是说,所有项目的目录都将构建操作"设置为资源".

Is there a way, in WPF, to enumerate through all files within a specific embedded resource directory? That is, a directory of items all having a "Build Action" set to "Resource".

推荐答案

资源被编译成一个名为 YourAssemblyName.g.resources 的资源流.所以,我们加载这个流,它看起来是一个字典,其中键是资源名称,值是资源数据.我们对资源名称感兴趣,因为它(通常)是资源的原始文件夹和文件名.然后我们过滤掉那些以我们感兴趣的文件夹开头的键.

The resources are compiled into a resource stream named YourAssemblyName.g.resources. So, we load up this stream which appears to be a dictionary where the key is the resource name and the value is the resource data. We are interested in the resource name as that is (usually) the original folder and file name for the resource. We then filter out those keys that begin with the folder we are interested in.

public static string[] GetResourcesUnder(string folder)
{
    folder = folder.ToLower() + "/";

    var assembly       = Assembly.GetCallingAssembly();
    var resourcesName  = assembly.GetName().Name + ".g.resources";
    var stream         = assembly.GetManifestResourceStream(resourcesName);
    var resourceReader = new ResourceReader(stream);

    var resources =
        from p in resourceReader.OfType<DictionaryEntry>()
        let theme = (string)p.Key
        where theme.StartsWith(folder)
        select theme.Substring(folder.Length);

    return resources.ToArray();
}

LINQ 查询过滤掉所有以给定文件夹名称开头的资源键,并从键中删除文件夹名称.

The LINQ query filters out all the resource keys that start with the given folder name and also removes the folder name from the key.

您需要知道的一件事是 XAML 文件被编译并被赋予扩展名 BAML.因此,假设您在名为 Themes/Theme1.xamlThemes/Theme2.xaml 等的文件夹下有一堆资源字典.这些将被编译到您的程序集中如Themes/Theme1.bamlThemes/Theme2.baml

One thing you need to know is that XAML files get compiled and given the extension BAML. So, let's say you have a bunch of resource dictionaries under a folder named Themes/Theme1.xaml, Themes/Theme2.xaml, etc. These will get compiled into your assembly as Themes/Theme1.baml, Themes/Theme2.baml, etc.

这篇关于枚举嵌入资源目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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