What is File Exception Handling in C#.Net?
As we all know whenever we are working on files in c#.net there are very bright chances that exception may occur while processing the files, so handling the exception is very important and crucial operation. So here the type of exception handeling while working in files are FileNotFoundException. DirectoryNotFoundException, IOException. Please check the detail about each type of file exceptions:- FileNotFoundException: This exception whenever we are trying to access a file from a directorryy and it is not available.
- DirectoryNotFoundException: This exception occurs when we try to access a directory or try to read it is not available on the provided location.
- IOException: This exception occurs whenever we try to access or read or write a file ant it is not accessible IO exception will occur.
How to Handel Exception C#.Net for Files?
Here we will check how we can handle the exception when it happens while working with files. Here we will check with a simple example in c#.net. Let's suppose we have a directory and few files in it. We will refer the below directory mention.
Here in this directory, we are having a file on the given path. Now let's check each and every type of example wit and example in c#.net.
try
{
string filePath = "D:\\DemoProject\\DemoFolder\\codemantra99_Test.txt";
StreamReader readFile = new StreamReader(filePath);
var data = readFile.ReadLine();
readFile.Close();
}
catch (FileNotFoundException fe)
{
Console.WriteLine("File file not found." + fe.InnerException);
}
In above code I have change the file name in the given path and tried to read the file with StreamReader. Here we will get an exception. Refer the below image.2. DirectoryNotFoundException: Here we will check a simple example with a code where we will change the directory name and get try to access.
try
{
string folderPath = "D:\\DemoProject\\DemoFolder_Test";
Directory.GetFiles(folderPath);
}
catch (DirectoryNotFoundException fe)
{
Console.WriteLine("Directory not found." + fe.InnerException);
}
In above sample code I have taken a path which does not exists and trying to read the file list from the directory. Here we will get exception for directory.
try
{
string filePath = "D:\\DemoProject\\DemoFolder\\test.docx";
File.Delete(filePath);
}
catch (IOException fe)
{
Console.WriteLine("File being used by another process." + fe.InnerException);
}
Now open the text file and execute the code. In above detail I have shared what is exception in c#.net while working on files and what the different type of exception. Now what are the best practices which we follow the avoid the exception to handle it in such a way so that it should not become a pain point for the end user.
Verify the File Exists or Not
To handle the file existence exception, we need to follow two processes. First to user File.Exists(Path) to check file exists or not. and second one is try, catch block. Combination of both will be the best. Here use off File.Exists(Path) to avoid the exception.
try
{
string filePath = "D:\\DemoProject\\DemoFolder\\codemantra99_test.txt";
if (File.Exists(filePath))
{
StreamReader readFile = new StreamReader(filePath);
var data = readFile.ReadLine();
readFile.Close();
}
else
{
Console.WriteLine("File not found.");
}
}
catch (FileNotFoundException fe)
{
Console.WriteLine("Exception:" + fe.InnerException);
}
Here I have changed the file name. Now to avoid the exception I have verified the file exists or not by using File.Exists(Path).
Verify the Folder exists or Not
Here if we are excepting a directory exists or not exception, the best way to use Directory.Exists(Path) to verify the file exists not. If it does not exists display a message and also use, try catch block to capture if any exception occurred. Here in below code i have changed the directory name and tried to read the file form the directory.
try
{
string folderPath = "D:\\DemoProject\\DemoFolder_Test";
if (Directory.Exists(folderPath))
{
Directory.GetFiles(folderPath);
}
else
{
Console.WriteLine("Directory not found." );
}
}
catch (DirectoryNotFoundException fe)
{
Console.WriteLine("Exception:" + fe.InnerException);
}
In above code i have used Directory.Exists(Path) to verify the folder path exits or not. Now lets run the code the check the output.
Use of try, catch and finally block
Check the below code. In this code I have used IOException and displayed a user-friendly message to user.
try
{
string filePath = "D:\\DemoProject\\DemoFolder\\test.docx";
File.Delete(filePath );
}
catch (IOException fe)
{
Console.WriteLine("File being used by another process.");
Console.ReadLine();
}
Here is the output.