Warm tip: This article is reproduced from stackoverflow.com, please click
.net c# exception file

File handling exceptions

发布于 2020-04-11 11:57:02

In a .NET console application, a file is being opened for reading, inside a try/catch block. The user should be alerted with a message printed to the console, if the file is open, or if it doesn't exist. The messages should be separated for each case. How can this be achieved? Using System.IOException doesn't differentiate between these two cases, if it is like the following:

try
{
    // open the file
}
catch (System.IOException)
{
    // print a message (Console.WriteLine)
}
Questioner
Al2110
Viewed
83
Anu Viswan 2020-02-02 11:40

If you would like to the Try-Catch approach, you could use FileNotFoundException to check if the exception was raised as specified file/path could not be found

try
{
  // Attempt Opening the file
}
catch (FileNotFoundException e)
{
  // File Not Found
}
catch(IOException e) when (e.Message.Contains($"The process cannot access the file '{filePath}' because it is being used by another process"))
{
  // File being used by another process
}
catch(IOException e) 
{
  // An I/O error occurred while opening the file (could be any other reason)
}

Futhermore, you could filter the IOException to ensure the particular error is due to the fact the file is being used by any other process.

Alternatively, you could also use File.Exists to check if the File Exists before attempting to open the file.

if(File.Exists(filePath))
{
   try
   {
     // File Exist, open the file
   }
   catch(IOException e)
   {
     // Error opening the file
   }
}
else
{
  // File do not exist
}