Search code examples
c#file-ioioinputstream

Catching IOException


I am writing a C# application in which I have to display a message if File is already being used by some process and if the file doesnot exist, the application needs to display another message.

Something like this:

try 
{
    //Code to open a file
}
catch (Exception e)
{
    if (e IS IOException)
    {
        //if File is being used by another process
        MessageBox.Show("Another user is already using this file.");

        //if File doesnot exist
        MessageBox.Show("Documents older than 90 days are not allowed.");
    }
}

Since IOException covers both the conditions, how do I distinguish if this exception is caught because of File being used by another process or File doesnot exist?

Any help would be highly appreciated.


Solution

  • As you can see here File.OpenRead can throw these exception type

    1. ArgumentException
    2. ArgumentNullException
    3. PathTooLongException
    4. DirectoryNotFoundException
    5. UnauthorizedAccessException
    6. FileNotFoundException
    7. NotSupportedException

    for each of this exception type you can handle it in this way

    try{
    
    }
    catch(ArgumentException e){
      MessageBox.Show("ArgumentException ");
    }
    catch(ArgumentNullExceptione e){
     MessageBox.Show("ArgumentNullExceptione");
    }
    .
    .
    .
    .        
    catch(Exceptione e){
         MessageBox.Show("Generic");
    }
    

    In your case you can handle just one or two types and other are always catched by generic Exception (it must be always the lastone because cathces all Exceptions)