取消openfiledialog时如何防止异常?

Fuz*_*ans 8 c# file-io image exception openfiledialog

我的程序有一个按钮,当点击它打开一个openfiledialog来选择一张图片:

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();
}
Run Code Online (Sandbox Code Playgroud)

使用dialogresult框上的检查还没有解决我的问题:

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; 
Run Code Online (Sandbox Code Playgroud)

如果我选择图片并完成文件选择,代码可以正常工作.但是,如果我在两者之间的任何时候取消该过程,我会得到例外情况"路径不是合法形式".我不确定哪个部分我想象我可以用a来处理这个问题try-catch,但是我不肯定哪个部分导致了这个问题?如果我try catch调用ChoosePicture()方法,我至少可以阻止它崩溃程序,但是当fdialogbox中没有选择图片时仍然会抛出异常.

Ant*_*haw 14

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
Run Code Online (Sandbox Code Playgroud)

另外,FileName已经是一个字符串,所以不需要使用.ToString()

编辑:固定缩进