解決GetManifestResourceNames()無法讀取資源文件

//讀取資源文件中的圖片並輸出流,String resource是資源文件名;

        public static Image GetImage(string name)
        {
            name = "Spymaster.Resources." + name;  // "Spymaster.Resources.resources.mainboard.png"

            // "Spymaster.Properties.Resources.resources"
            string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames();
            for (int i = 0; i < names.Length; i++)
            {
                if (names[i].Replace('\\', '.') == name)
                {
                    using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(names[i]))
                    {
                        // "You must keep the stream open for the lifetime of the Image."
                        Image image = Image.FromStream(stream);

                        // so we just create a copy of the image 
                        Bitmap bitmap = new Bitmap(image);

                        // and dispose it right here
                        image.Dispose();

                        return bitmap;
                    }
                }
            }

            return new Bitmap(1, 1);
        }

以上代碼無錯,但是讀不出資源文件,解決方法:

一般情況都項目工程中都有Resources目錄,當你加了圖片文件後,會自然加到這個文件到這個目錄下,請點這個文件,然後選擇“屬性”,“生成操作”選擇“嵌入的資源",問題解決!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章