Create an error message for DirectoryNotFoundException in C# instead of crashing

467 Views Asked by At

I have a program that uses a folderBrowser to locate a file but adds some pre-existing folders to the end of it.

Example:

System.IO.DirectoryInfo directoryName = new DirectoryInfo(@folderBrowser.SelectedPath + "/folder1/folder2/");

But if someone doesn't use the folderBrowser (which they should have) and clicked the Go button, the program will crash and throw an exception.


So what I want to do is use a MessageBox.Show to let the user know that they haven't chosen a folder in the folderBrowser and then cancel the button press so they can choose a folder.

1

There are 1 best solutions below

0
On

Just use the try-catch statement

 try{

     System.IO.DirectoryInfo directoryName = new DirectoryInfo(@folderBrowser.SelectedPath + "/folder1/folder2/");
    }
    catch(DirectoryNotFoundException ex)  
    {
       MessageBox.Show("Folder not found")
    }