Pyroglyph
Pyroglyph

Reputation: 179

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

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.

Upvotes: 0

Views: 461

Answers (1)

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13764

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")
    }

Upvotes: 2

Related Questions