gpt4 book ai didi

c# - 取消打开文件对话框时如何防止异常?

转载 作者:太空狗 更新时间:2023-10-29 18:08:40 25 4
gpt4 key购买 nike

我的程序有一个按钮,单击该按钮会打开一个打开文件对话框以选择图片:

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();
}

检查对话框结果框也没有解决我的问题:

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;

如果我确实选择了一张图片并完成了文件选择,则该代码有效。但是,如果我在中间的任何时候取消该过程,我都会得到异常“路径不是合法形式”。我不确定我认为哪一部分可以用 try-catch 来处理,但是我不确定是哪一部分导致了这个问题?如果我在对 ChoosePicture() 方法的调用周围放置一个 try catch,我至少可以阻止它使程序崩溃,但是当没有图片时仍然会抛出异常在 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

此外,FileName 已经是一个字符串,因此无需在其上使用 .ToString()

编辑:固定缩进

关于c# - 取消打开文件对话框时如何防止异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8749655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com