我的文本编辑器程序在打开对话框时遇到了一些问题,当你实际选择一个文件时它可以正常工作,但如果你取消它会引发异常,如图所示:
openFileDialog1.ShowDialog();
if (saveFileDialog1.InitialDirectory.Equals(saveFileDialog1.RestoreDirectory))
{
MessageBox.Show("Didnt make a selection");
}
else
{
txtUI.Text = File.ReadAllText(openFileDialog1.FileName);
}
saveFileDialog1.FileName = "Please click on the file you want to open";
我尝试了这个if-else语句,但它似乎不起作用。
答案 0 :(得分:1)
您需要检查ShowDialog()
的返回值:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// do your stuff
}
如果用户取消了对话框,则结果为DialogResult.Cancel
。
答案 1 :(得分:0)
将你的代码放在像这样的try catch块中
try{
if (saveFileDialog1.InitialDirectory.Equals(saveFileDialog1.RestoreDirectory))
{
MessageBox.Show("Didnt make a selection");
}
else
{
txtUI.Text = File.ReadAllText(openFileDialog1.FileName);
}
saveFileDialog1.FileName = "Please click on the file you want to open";
}catch{}