如何防止一个例外,当我取消一个OpenFileDialog? [英] How can I prevent an exception when I cancel an openfiledialog?
问题描述
我的程序有点击它时,会打开一个OpenFileDialog选择照片的按钮:
私人字符串ChoosePicture()
{
fDialog.Title =选择图片;
fDialog.Filter =图像文件(* .BMP,* .GIF,* .JPG)| * .BMP; * .gif注意*; * JPG
fDialog.InitialDirectory =C:;
fDialog.ShowDialog();
fDialog.AddExtension = TRUE;
fDialog.CheckFileExists = TRUE;
fDialog.CheckPathExists = TRUE;
//返回目录
返回fDialog.FileName.ToString一个字符串();
}
使用上的DialogResult复选框勾并没有解决我的问题之一:
fDialog.AddExtension = TRUE;
fDialog.CheckFileExists = TRUE;
fDialog.CheckPathExists = TRUE;
的DialogResult RES = fDialog.ShowDialog();
如果(RES == DialogResult.OK)
{
//返回目录
返回fDialog.FileName.ToString一个字符串();
}
返回NULL;
如果我做选择照片,然后完成文件选择代码工作。但是如果我取消了该过程在我之间得到例外的任何一点的道路是不合法的形式。我不知道我想象的哪一部分,我可以照顾这跟一个try-catch,但是我还不能肯定这部分导致了问题?如果我把一个尝试捕捉在调用ChoosePicture()方法的时候,我至少可以从崩溃程序停止,但是当在fdialogbox没有选择画面仍在抛出的异常。
DialogResult的结果= fileDialog.ShowDialog();
如果(结果== DialogResult.OK){
//返回目录
返回fDialog.FileName的字符串;
}
返回NULL; //不知道他们是否取消
你会返回一个
此外,文件名已经是一个字符串,所以没有需要使用的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屋!