Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - How to get all images in the resources as list?

I have a WinForms project and added multiple images to the resources (project properties -> Resources). Now I have a Form1.cs, a UserControl1.cs with a .resx files, and using Assembly.GetManifestResourceNames(), it contains 3 strings namely:

1 TestApplication1.Properties.Resources.resources, 2 TestApplication1.Form1.resources 3 TestApplication1.UserControl1.resources

What I need to get now is obviously the files from #1 which contains the images I need to get. What I need to do is have a list that I can access these images through their indexes. I can access this files individually with no problem, but I have 72 images so I need them as a list. So my question is, how do I get these images in #1 as a list?

EDIT: Is there no other way as to create a list and add all of my 72 images to it? Or is there some way that I can get all of these images from the resources as a list? Also, I don't want to resort to using System.IO as I will build this application as a Class Library.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

To get all images in a resx file, you can use either of these options:

ResourceManager.GetResourceSet

Based on Dai's answer you can use ResourceManager.GetResourceSet and then filter and shape the the result this way:

var images = Properties.Resources.ResourceManager
                       .GetResourceSet(CultureInfo.CurrentCulture, true, true)
                       .Cast<DictionaryEntry>()
                       .Where(x => x.Value.GetType() == typeof(Bitmap))
                       .Select(x => new { Name = x.Key.ToString(), Image = x.Value })
                       .ToList();

Reflection

Also, as another option you can use reflection on the type of your resource and find properties and shape the result this way:

var images = typeof(Properties.Resources)
               .GetProperties(BindingFlags.Static | BindingFlags.NonPublic |
                                                    BindingFlags.Public)
               .Where(p => p.PropertyType == typeof(Bitmap))
               .Select(x => new { Name = x.Name, Image = x.GetValue(null, null) })
               .ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...