簡體   English   中英

從資源加載圖像時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中圖像的屬性,並確保“復制到輸出目錄”為“如果較新則復制”或“始終復制”。 這是一個截圖(在我的例子中,它是一個光標資源,但對於圖像也是一樣)。

在此輸入圖像描述

UPDATE

如果您已將圖像嵌入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);

來源

注意

您可以通過將屬性Build Action設置為Embedded Resource,將圖像嵌入二進制文件(通常是.exe),或者通過將Build Action設置為Content將它們保留為單獨的文件。 如果您保留為內容,請將“復制到輸出目錄”設置為“真”。

您的代碼中沒有任何內容可以說明文件的位置,因此默認情況下文件不在某處。 如果文件與exe位於同一位置,請嘗試類似imgNmae =“./ image0”+ i +“。png”;

調整相對路徑以考慮文件實際所在的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM