Trying to get filepath through Openfiledialogue

24 views Asked by At

I am writing code for button click on which using filedialogue the file opens and i am able to choose picture from it. then i want to extract the path of the file and store it in a string variable and pass that as argument ( here compiler throws exception: "A first chance exception of type 'System.IO.FileNotFoundException' occurred in System.Drawing.dll,Additional information: OK" ), as for my code i need the path dynamically so that everytime similar picture doesn't showup ..

//choose image from file
public void select_image_button17_Click(object sender, EventArgs e) {

            foreach (Button b in game_panel1.Controls)
            {
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                 openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
                string a = "";
                a = openFileDialog1.ShowDialog().ToString();
                string directoryPath = Path.GetDirectoryName(a);

                Image ToBeCropped = Image.FromFile(a,true);//exception
                ReturnCroppedList(ToBeCropped, 320, 320);
                pictureBox1.Image = ToBeCropped;
                pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                AddImagesToButtons(images);

            }
    }
1

There are 1 answers

0
itsme86 On BEST ANSWER

The FileName property will be set when the dialog returns with an OK status.

if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
    // User cancelled out of dialog
}
else
{
    string filename = openFileDialog1.FileName;
}