bob dylan
bob dylan

Reputation: 687

C#: FileNotFoundException when loading images from resource

I am trying to load in a bunch of images from my resource file but I am getting the FileNotFoundException for some reason. the Image names are like so: "image01.png", "image02.png", ... , "image10.png", image11.png"

In the end I want to be able to display all of the images on the screen.

Here is what I have:

  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); }
}

Here is a sample error output that I am getting:

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

Screenshot: updated code

I have also fixed a type on line 56 from: "PictureForm.PuzzleForm." to "PicturePuzzle." but still no luck.

Upvotes: 1

Views: 3412

Answers (2)

C. Knight
C. Knight

Reputation: 749

There's nothing in your code to say where the files are located so it's defaulting to somewhere the files aren't. If the files sit in the same location as your exe then try something like imgNmae = "./image0" + i + ".png";

adjusting the relative path to account for where the files actually sit.

Upvotes: 0

Eric J.
Eric J.

Reputation: 150198

You are not specifying a path to load the file from. They will be loaded from where the assembly is running.

Note that Image.FromFile does not load an embedded resource, but rather the .png from disk. I assume this is what you intend.

Check the properties for the images in Visual Studio and ensure that Copy to Output Directory is Copy if Newer or Copy Always. Here's a screenshot (in my case it's a cursor resource, but same idea for an image).

enter image description here

UPDATE

If you have embedded your images in your EXE or another file, you can use code similar to

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)

NOTE

You can either embed your images in a binary file (commonly your .exe) by setting the property Build Action to Embedded Resource, or leave them as separate files by setting Build Action to Content. If you leave as content, set Copy to Output Directory to True.

Upvotes: 3

Related Questions