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.
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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With