枚举嵌入资源目录中的文件

发布于 2024-10-18 10:41:43 字数 65 浏览 4 评论 0原文

在 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".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随风而去 2024-10-25 10:41:43

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

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

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

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

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

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文