-1

I have a bit of a problem with my text editor program with the open dialog,it works perfectly when you actually select a file but if you cancel out it throws an exception as shown:

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

I have tried this if-else statement but it doesn't seem to work.

Sarath S Menon
  • 2,168
  • 1
  • 16
  • 21

2 Answers2

1

You need to check the return value of ShowDialog():

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    // do your stuff
}

If the user cancelled the dialog, the result would be DialogResult.Cancel.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
0

Put your code in try catch block like this

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{}
Amit Yadav
  • 481
  • 3
  • 11