捕获IOException

时间:2014-12-01 11:03:37

标签: c# file-io io inputstream

我正在编写一个C#应用程序,如果某个进程已经使用了File,我必须显示一条消息,如果该文件不存在,则应用程序需要显示另一条消息。

这样的事情:

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.");
    }
}

由于IOException涵盖了这两个条件,我如何区分是否由于另一个进程使用File或文件不存在而捕获到此异常?

任何帮助都将受到高度赞赏。

4 个答案:

答案 0 :(得分:2)

始终从最具体到最常见的异常类型中捕获。 每个异常都会继承Exception - 类,因此您将在catch (Exception)语句中捕获任何异常

这将分别过滤IOExceptions和其他所有内容:

catch (IOException ioEx)
{
     HandleIOException(ioEx);
}
catch (Exception ex)
{
     HandleGenericException(ex);
}

所以抓住Exception总是持续的。检查是否可能,但不常见。

关于您的问题:

if (File.Exists(filePath)) // File still exists, so obviously blocked by another process

这是分离条件的最简单的解决方案。

答案 1 :(得分:2)

如您所见here File.OpenRead可以抛出这些异常类型

  1. ArgumentException
  2. ArgumentNullException
  3. PathTooLongException
  4. DirectoryNotFoundException
  5. UnauthorizedAccessException
  6. FileNotFoundException
  7. NotSupportedException
  8. 对于每种此异常类型,您都可以通过这种方式处理它

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

    在你的情况下,你只能处理一种或两种类型,而其他类型总是被通用的Exception捕获(它必须始终是最后一种,因为所有异常都是阴道)

答案 2 :(得分:0)

尝试以下方法:

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.");
}

更多信息:http://www.dotnetperls.com/ioexception

答案 3 :(得分:-1)

当文件不存在时,它将抛出继承IOException的FileNotFoundException,所以你可以像这样写:

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.");
}
相关问题