Search code examples
c#openfiledialog

How to prevent an exception when canceling an OpenFileDialog?


I click on the button to upload a photo. When I cancel the photo selection, the program throws an exception.

Here's my code:

private void button1_Click(object sender, EventArgs e)
{
    Image<Bgr, byte> img = new Image<Bgr, byte>(Islem.getFileName());
    ımageBox1.Image = img;
}

class Islem
{
    public static string getFileName()
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + "All files (*.*)|*.*";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            return ofd.FileName;
        }
        return "";
    }
}

How to fix this situation?


Solution

  • When the user cancels the dialog, your getFileName function returns an empty string. Therefore, you get an exception when you try to load the image from a path that doesn't exist (i.e., the empty string). If you read the exception message, you would figure it out yourself.

    You can do something like this:

    private void button1_Click(object sender, EventArgs e)
    {
        string imgFilePath = Islem.getFileName();
        if (!string.IsNullOrEmpty(imgFilePath))
        {
            Image<Bgr, byte> img = new Image<Bgr, byte>(imgFilePath);
            ımageBox1.Image = img;
        }
    }
    

    That would only use the file path (i.e., load the image) if the returned string isn't empty.

    Alternatively, you can check if the file exists:

    if (System.IO.File.Exists(imgFilePath)) { //use it to load the image }