Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
949 views
in Technique[技术] by (71.8m points)

wpf - Enumerating .NET assembly resources at runtime

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

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...