C#:从资源加载图像时出现 FileNotFoundException

C#: FileNotFoundException when loading images from resource

我正在尝试从我的资源文件中加载一堆图像,但由于某种原因我收到了 FileNotFoundException。图像名称是这样的: "image01.png", "image02.png", ..., "image10.png", image11.png"

最后我希望能够在屏幕上显示所有图像。

这是我的资料:

  String imgName;
        int row = 0, col = 0;

        for (int i = 1; i <= 15; i++)
        {
            //get the name of the current image
            if (i < 10)
                imgName = "image0" + i + ".png";
            else
                imgName = "image" + i + ".png";

            Image img = null;
            try { 
                img = Image.FromFile(imgName);//read the image from the resource file
            }
                catch (Exception e) { Console.WriteLine("ERROR!!!" + e); }
}

这是我得到的示例错误输出:

ERROR!!!System.IO.FileNotFoundException: tile01.png
   at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
   at System.Drawing.Image.FromFile(String filename)

截图:

我还在第 56 行修复了一个类型:"PictureForm.PuzzleForm." 到 "PicturePuzzle." 但仍然没有成功。

您没有指定加载文件的路径。它们将从程序集所在的位置加载 运行.

请注意 Image.FromFile 不加载嵌入资源,而是从磁盘加载 .png。我想这就是你想要的。

检查 Visual Studio 中图像的属性并确保“复制到输出目录”是“如果较新则复制”或“始终复制”。这是一个屏幕截图(在我的例子中它是一个光标资源,但图像的想法相同)。

更新

如果您已将图像嵌入到 EXE 或其他文件中,则可以使用类似于

的代码
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = 
    thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");
this.pictureBox1.Image = Image.FromStream(file);

(Source)

注意

您可以通过将 属性 Build Action 设置为 Embedded Resource 将您的图像嵌入二进制文件(通常是您的 .exe),或者通过将 Build Action 设置为 Content 将它们保留为单独的文件。如果您保留内容,请将“复制到输出目录”设置为“真”。

您的代码中没有说明文件所在的位置,因此它默认位于文件所在的位置。如果文件与您的 exe 位于同一位置,请尝试类似 imgNmae = "./image0" + i + ".png";

调整相对路径以说明文件的实际位置。