Search code examples
c#wpfexceptionnullopenfiledialog

C# OpenFileDialog - exception when no files are chosen


I am trying to work out on this error, when no files are chosen the program obviously goes to do next step although it shouldn't. I have tried:

if (fileToCheck != null)

but it didn't work. Any other suggestions?

private void Mail(object sender, RoutedEventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

    if (openFileDialog.ShowDialog() == true)
    {
            spamText.Text = File.ReadAllText(openFileDialog.FileName);               
    }


    string[] fileToCheck = { openFileDialog.FileName };

    Splitter(fileToCheck);
    mail = tempDict;
}

Solution

  • You was on the right track.

    But checking if (fileToCheck != null) is not enough, since when no file is selected, openFileDialog.FileName contains empty string, not null.

    So you can use if (!String.IsNullOrEmpty(fileToCheck)) check.

    Another way - just put the code around fileToCheck which is currently outside of openFileDialog.ShowDialog() == true condition just inside of it. It looks more logical, since if file not selected, this condition will not be hit and you don't need to proceed with additional check.

    So your code could look like

    if (openFileDialog.ShowDialog() == true)
    {
        string fileName = openFileDialog.FileName;
        if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
        {
            spamText.Text = File.ReadAllText(fileName);               
            Splitter(new [] {fileName});
        }
    }