当我取消openfiledialog时如何防止异常? [英] How can I prevent an exception when I cancel an openfiledialog?
问题描述
我的程序有一个按钮,当点击打开一个openfiledialog来选择图片:
私人字符串ChoosePicture()
{
fDialog.Title =选择图片;
fDialog.Filter =图像文件(* .bmp,* .gif,* .jpg)| * .bmp; * .gif *; *。
fDialog.InitialDirectory =C:;
fDialog.ShowDialog();
fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
//返回目录的字符串
return fDialog.FileName.ToString();
}
使用对话框中的检查框还没有解决我的问题: / p>
fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
DialogResult res = fDialog.ShowDialog();
if(res == DialogResult.OK)
{
//返回目录的字符串
return fDialog.FileName.ToString();
}
返回null;
如果我选择图片并完成文件选择,代码可以工作。但是,如果我在任何时候取消进程,我得到例外路径不是法律形式。我不知道我想到哪个部分我可以用 try-catch
来处理这个问题,但是我不是积极的,哪一部分是导致这个问题的?如果我在 ChoosePicture()
方法的调用周围放置一个 try catch
,我至少可以阻止它崩溃程序,但是在fdialogbox中没有选择图片时,仍然会抛出异常。
DialogResult result = fileDialog.ShowDialog();
if(result == DialogResult.OK){
//返回目录的字符串
return fDialog.FileName;
}
返回null; //不知道如果它们取消
,则FileName已经是一个字符串,所以没有需要使用 .ToString()
编辑:固定缩进
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
这篇关于当我取消openfiledialog时如何防止异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!