Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent an exception when I cancel an openfiledialog?

My program has a button which when clicked opens an openfiledialog to choose a picture:

private string ChoosePicture()
{         
    fDialog.Title = "Select Picture";
    fDialog.Filter = "Image Files (*.bmp, *.gif, *.jpg)|*.bmp; *.gif*;*.jpg";
    fDialog.InitialDirectory = "C:";
    fDialog.ShowDialog();

    fDialog.AddExtension = true;
    fDialog.CheckFileExists = true;
    fDialog.CheckPathExists = true;

    //returns a string for the directory
    return fDialog.FileName.ToString();
}

Using a check on the dialogresult box hasn't resolved my issue either:

fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;

DialogResult res = fDialog.ShowDialog();
if (res == DialogResult.OK)
{                
    //returns a string for the directory
    return fDialog.FileName.ToString();
}

return null; 

The code works if I do choose a picture and complete the file selection. However if I cancel the process at any point in between I get the exception "The path is not of a legal form". I am not sure which part I imagine I could take care of this with a try-catch, however I'm not positive which part is causing the issue? If I put a try catch around the call to the ChoosePicture() method, I can at least stop it from crashing the program but the exception is still being thrown when no picture is selected in the fdialogbox.

like image 508
Fuzz Evans Avatar asked Jan 05 '12 20:01

Fuzz Evans


2 Answers

DialogResult result = fileDialog.ShowDialog();
if (result == DialogResult.OK) {

     //returns a string for the directory
     return fDialog.FileName;
}

return null; //not sure what you will return if they cancel

also, FileName is already a string, so no need to use .ToString() on it

EDIT: fixed indenting

like image 162
Anthony Shaw Avatar answered Sep 28 '22 10:09

Anthony Shaw


Check the dialog result and act accordingly:

private string ChoosePicture()
{         

        fDialog.Title = "Select Picture";
        fDialog.Filter = "Image Files (*.bmp, *.gif, *.jpg)|*.bmp; *.gif*;*.jpg";
        fDialog.InitialDirectory = "C:";
        DialogResult res = fDialog.ShowDialog();

        if(res == DialogResult.OK)
        {
           fDialog.AddExtension = true;
           fDialog.CheckFileExists = true;
           fDialog.CheckPathExists = true;

           //returns a string for the directory
           return fDialog.FileName.ToString();
        }            
        else
        {
           return null; // or something
        }
}
like image 21
Tudor Avatar answered Sep 28 '22 10:09

Tudor