文件路径为空时(取消OpenFiledDalog时)的异常

时间:2014-04-20 04:05:22

标签: c# exception openfiledialog

这是代码:

OpenFileDialog openFileDialog1 = new OpenFileDialog();

        DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
        if (result == DialogResult.OK) // Test result.
        {
            string file = openFileDialog1.FileName;

        }
        else { MessageBox.Show("Error."); }

//later on..
        DataTable lertableEC0 = new DataTable();
        lertableEC0.ReadXml(openFileDialog1.FileName);

并且在这里最终出现错误,一切正常,xml导入等,只有当我在打开的对话框中取消我得到异常,任何提示?

(有一个类似的问题,但答案对我来说仍然很混乱

  return null;    

对我不起作用

2 个答案:

答案 0 :(得分:1)

当您取消对话框时,FileDialog.FileName""(空字符串),因为未选择任何内容

要解决此问题 - 例如如果没有选择文件,则不执行任何操作 - 确保仅在“ if OK对话框结果”逻辑中使用FileName。

DataTable lertableEC0 = new DataTable();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) {
    // -> openFileDialog1.FileName is not empy here
    lertableEC0.ReadXml(openFileDialog1.FileName);
} else {
    // -> openFileDialog1.FileName is empty here
    MessageBox.Show("Error.");
}
// -> openFileDialog1.FileName may or may not be empty here

答案 1 :(得分:1)

  if (result == DialogResult.OK) // Test result.
  {
        string file = openFileDialog1.FileName;

        DataTable lertableEC0 = new DataTable();
        lertableEC0.ReadXml(openFileDialog1.FileName);       
  }
 else { 
       MessageBox.Show("Error.");
  }

如果单击“取消”按钮,则未设置文件名,因此将空字符串传递给ReadXml()函数,该函数将引发异常。因此,您必须在OK单击条件

中移动该功能
相关问题