Search code examples
c#exceptionopenfiledialog

Exception when a path to a file is null (when you cancel OpenFiledDalog)


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


Solution

  •   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