Fuzz Evans Fuzz Evans - 10 days ago 8
C# Question

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.

Answer
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