WPF C# Reflection: Iterate over all resources with

2019-03-06 17:49发布

问题:

I have a .dll with a lot of ResourceDictionaries.

The build action of all these ResourceDictionaries is set to "Page".

Inside the Dll, I want to find all these ResourceDictionaries and iterate over them.

If I set the build action to "EmbeddedResource", I can use Reflection:

var embeddedResources = Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList();

But GetManifestResourceNames() does not work for resources with build action "Page".

How do I find or iterate over all resources that have the build action "page"?

The solution doesn't have to be Reflection. Any other way is very welcome.

Thank you!

Solution:

Ladies and Gentleman! I have to announce, that the man of the week and the winner of this bounty, is Mr. Jon Wu. Jon Wu gave the right hint and through searching, I found this solution:

Enumerating .NET assembly resources at runtime

The working code, slightly changed looks like this:

public static string[] GetResourceNames()
    {
        var asm = Assembly.GetExecutingAssembly();
        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();
        }
    }

If you call this method, you get all the resource strings with a ".baml" at the end and you can iterate over them.

Thank you Jon Wu for the right hint.

回答1:

According to this answer,

Page (WPF only): Used to compile a xaml file into baml. The baml is then embedded with the same technique as Resource (i.e. available as AppName.g.resources).

So it sounds like you just need to look for resources identified with YourAppName.g.resources.