Question

I am getting a System.IO.FileNotFoundException error when I run this code. Have I done something drastically wrong in the code or is there something small that I haven't thought of yet?

I have made sure everything has permission and the file is definitely present and the correct file type.

public Form1()
{
    InitializeComponent();

    DirectoryInfo ImgD = new DirectoryInfo("C:/Users/Dan/ImgDirectory/");
    FileInfo[] rgFiles = ImgD.GetFiles("*.jpg");
    foreach (FileInfo fi in rgFiles)
    {
        listBox1.Items.Add(Path.GetFileNameWithoutExtension(fi.Name));
    }
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    pictureBox1.Image = System.Drawing.Image.FromFile(
        @"C:/Users/Dan/ImgDirectory/" + listBox1.SelectedItem.ToString());
}
Was it helpful?

Solution

You are populating the Listbox with file names without extensions.

So in this line you need to append the extension again:

pictureBox1.Image = System.Drawing.Image.FromFile(@"C:/Users/Dan/ImgDirectory/" + listBox1.SelectedItem.ToString());

So it becomes this:

pictureBox1.Image = System.Drawing.Image.FromFile(@"C:/Users/Dan/ImgDirectory/" + listBox1.SelectedItem.ToString() + ".jpg");

As a side note, this sort of error can be easily detected if you use debug break points. Since that line was the one giving you trouble you should put a break point there and start debug (F5). When the code stops at that break point you can check the value of @"C:/Users/Dan/ImgDirectory/" + listBox1.SelectedItem.ToString()) and you would've found the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top