Database Reference
In-Depth Information
}
}
Build the application, and press Ctrl+F5 to run it. If you pass the wrong file name this time, it will
actually throw an exception, but we are handling that, so a user-friendly message will be shown, as in
Figure 11-12.
Figure 11-12. Exception handling with a catch block
As you can see, this dialog shows that you entered a wrong path or file name. Click OK, and it will
take you back to the application for you to modify the path or file name correctly.
In such a file-handling applications, another scenario is when the user passes the wrong directory
name. To handle that, you need a separate catch block to handle DirectoryNotFoundException . You have
already added that, as shown in Listing 11-3. To test it now, change the path to a nonexisting folder
name, and you will see a separate dialog saying “Provide valid Directory name.”
How It Works
This file-read code is based on the Stream object, so you need to create a StreamReader object.
StreamReader sr=null;
Now you use this object in the try block to pass the file path and file name for reading the content.
try
{
sr = new StreamReader(txtFileReadPath.Text);
txtFileContent.Text = sr.ReadToEnd();
}
If a wrong file path or file name is provided, then it will throw a FileNotFoundException , so you need
to provide a catch block to handle the exception.
catch (FileNotFoundException ex)
{
MessageBox.Show(ex.Message + " " + "Please provide valid path and filename");
}
If a wrong directory name is provided, then it will throw a DirectoryNotFoundException , so you need
to provide a catch block to handle the exception.
 
Search WWH ::




Custom Search