talbright
talbright

Reputation: 446

Loading Array of Images

I have a set of images on a windows form. I want to add an image to an array when a checkbox corresponding to an image is checked. Everytime I check the box it says "FileNotFoundException was unhandled."

public partial class FrmSignage : Form
{
    Image[] images = new Image[12];
    int i = 0;
    public FrmSignage()
    {
        InitializeComponent();
    }

    private void chkRadiation_CheckedChanged(object sender, EventArgs e)
    {
        images[i] = Image.FromFile("radiation.gif");   
        i++;
    }

The error is thrown on the line "images[i] = Image.FromFile("radiation.gif");". The filename is correct. What could I be missing?

Thanks in advance.

Upvotes: 1

Views: 24392

Answers (3)

RobV
RobV

Reputation: 28675

The problem is that the file is not found relative to the running code. Even if the file exists in your environment because it is a relative path it must exist relative to the running code.

One way to do this is that assuming you have the image as a project item you can change the build action for it to Content and set the copy to output directory as Copy if Newer (these options can be found in the Properties window for an item)

You should also add some error handling to your code because what's to stop your users from deleting the image even if you've ensured it is in the right place?

Upvotes: 0

MgSam
MgSam

Reputation: 12813

You should make sure the path "radiation.gif" makes sense. This will always check in the directory in which the executable is running.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564891

The filename is correct.

You need to supply the correct path to the file, as well. It is likely that the filename is correct, but the current directory is not what you expect.

By default, it will try to load the image from the same folder as the .exe - ie: Project\bin\Debug, but this can change at runtime. Loading an image without specifying the path is not safe because the current directory can be changed, so you should specify the full path.

The classes in System.IO, such as Path, provide quite a bit of functionality for building the proper path.

Upvotes: 3

Related Questions