【发布时间】:2015-01-29 09:00:36
【问题描述】:
我正在编写一个 C# 应用程序,如果文件已被某个进程使用,并且如果该文件不存在,则应用程序需要显示另一条消息。
类似这样的:
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被另一个进程使用还是File不存在而捕获了这个异常?
任何帮助将不胜感激。
【问题讨论】:
-
你确定它只是在这两种情况下都抛出
IOException吗?例如不是FileNotFoundException? (为什么要捕获Exception,然后使用is而不是在单独的捕获块中捕获IOException?) -
你知道你可以像这样使用 catch:
catch(IOException ioe){//handle ie exception}catch(Exception e){//handle unknown exception} -
FileNotFoundException 会在文件不存在时抛出。更多信息在这里:dotnetperls.com/ioexception
标签: c# file-io io inputstream