Catching an IOException
I am writing a C # application in which I need to display a message if a file is already in use by some process and if the file does not exist the application should display another message.
Something like that:
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
both conditions are covered, how can I tell if this exception is caught because the file is in use by another process or the file does not exist?
Any help would be much appreciated.
source to share
As you can see here, File.OpenRead can throw these types of exceptions.
- ArgumentException
- ArgumentNullException
- PathTooLongException
- DirectoryNotFoundException
- UnauthorizedAccessException
- FileNotFoundException
- NotSupportedException
for each of this type of exception, you can handle it 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 only handle one or two types and the others are always tracked by the generic Exception
(it should always be the last one because it contains all exceptions)
source to share
Always catch from the most generic type specific exceptions. Every exception inherits a class Exception
, so you will catch any exception in the statement catch (Exception)
.
This will filter out IOExceptions and all others separately:
catch (IOException ioEx)
{
HandleIOException(ioEx);
}
catch (Exception ex)
{
HandleGenericException(ex);
}
So the catch is Exception
always the last one. If checking is possible, but not general.
About your problem:
if (File.Exists(filePath)) // File still exists, so obviously blocked by another process
This would be the simplest solution to separate your conditions.
source to share
Try the following:
try
{
//open file
}
catch (FileNotFoundException)
{
MessageBox.Show("Documents older than 90 days are not allowed.");
}
catch (IOException)
{
MessageBox.Show("Another user is already using this file.");
}
More information: http://www.dotnetperls.com/ioexception
source to share
If the file doesn't exist, it will throw a FileNotFoundException, which inherits IOException, so you can write like this:
try
{
//file operate
}
catch (FileNotFoundException ex)
{
MessageBox.Show("Documents older than 90 days are not allowed.");
}
catch (IOException ex)
{
MessageBox.Show("Another user is already using this file.");
}
source to share