質問

This is the code:

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

and right here in the end comes the error, everything works fine, the xml import, etc only if i cancel in the open dialog i get the exception, any hint?

(there ir a similar question but the answer is still very confusing for me

  return null;    

didnt work for me

役に立ちましたか?

解決

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

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

Since filename is not set if Cancel button is clicked , empty string is passed to ReadXml() function which throws exception . So you have to move the function inside OK click condition

他のヒント

When you Cancel the dialog, FileDialog.FileName is "" (the empty string) because nothing was selected.

To handle this - e.g. don't do anything if no files were selected - make sure to only use FileName in the "if OK dialog result" logic.

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top