构建用作资源C#的图像的文件名

时间:2017-05-09 21:17:22

标签: c# winforms

尝试为资源文件夹中的图像构建文件名,并显示它的错误。 我将文件名创建为字符串参数, 已经创建了btn作为按钮'寻找" fileName "参数。 错误:错误1' warCards.Properties.Resources'不包含' fileName '的定义。 游戏是:战争(纸牌游戏) 谢谢你的帮助

  btn.Click += delegate(object sender, EventArgs e)
            {
                Random rnd = new Random();
                int num = rnd.Next(1, 14);
                int letter = 0;// represent random cards symbol 1-dimond 2-heart  3-spades 4-clubs
                string fileName = "_";
                if (num < 10 && num > 1)
                {
                    fileName = fileName + "0" + num.ToString() + "_of_";
                    if (isBlack)
                    {
                        letter = rnd.Next(1, 3);
                        if (letter == 1)
                        {
                            fileName += "spades";
                        }
                        else
                        {
                            fileName += "clubs";
                        }
                        //for example: try to create: _5_of_spades
                        btn.BackgroundImage = warCards.Properties.Resources.fileName;
                        btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
                        btn.Enabled = false;
                        isBlack = !isBlack;

                    }
                }
               };
                this.Controls.Add(btn);
                nextPos.X += 112;

            };

2 个答案:

答案 0 :(得分:0)

使用反射,您将能够从资源类型中检索属性。如果你能用其他方法解决它,你应该使用反射的情况很多。为了完成,这就是你如何使用反射来做到这一点:

        // Get a type reference of the Type containing the auto-generated resources from the .resx
        var resourceType = typeof(Properties.Resources);
        // Retrieve the information about the property containing the image
        var propertyReference = resourceType.GetProperty("_5_of_spades", BindingFlags.Static | BindingFlags.NonPublic);
        // Retrieve the value of the property
        var propertyValue = propertyReference.GetValue(null) as Image;

如评论中所述,您可以使用清单资源,它们包含项目中标记为构建操作的所有文件&#34;嵌入式资源&#34;设置而不是将其添加到Resources.resx文件中。 (所选项目项的属性窗格)。

如何读取嵌入资源并将其存储到Dictionary中的完整代码示例。

        // A dictionary to hold the images by their names
        var images = new Dictionary<string, Image>();

        // Read the resources of the currently executing assembly
        var assembly = Assembly.GetExecutingAssembly();
        // All the names of the files that have a "Build action = Embedded Resource"
        var names = assembly.GetManifestResourceNames();
        foreach (var name in names)
        {
            // Check if it's the resource we want
            if (name.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase))
            {
                // Create a 'sanitized name' which excludes the "{AssemblyName}.Resources." and ".png" part
                var prefix = $"{assembly.GetName().Name}.Resources.".Length;
                var sanitizedName = name.Substring(prefix, name.IndexOf(".png") - prefix);

                // Load the image from the Manifest Resource Stream
                var image = Image.FromStream(assembly.GetManifestResourceStream(name));

                // Add the image to the dictionary
                images.Add(sanitizedName, image);
            }
        }

        // ...

        // Retrieve the image from the dictionary by it's name
        button1.BackgroundImage = images["_5_of_spades"];

        // ...

        // If at any point forward you wish to unload the images from memory (Besides quiting the application)
        button1.BackgroundImage = null; // Make sure no controls use the image anymore
        Parallel.ForEach(images.Values, (image) => { image.Dispose(); });   // Cleanup in-memory images (Linq and TPL to make it a one-liner)

答案 1 :(得分:0)

我使用GetObject(string)方法完成了它。  谢谢大家