我正在编写一个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涵盖了这两种情况,那么如何区分这个异常是由于另一个进程使用的文件或者文件不存在而捕获的呢?
任何帮助都将不胜感激。
发布于 2014-12-01 11:13:01
如您所见,这里 File.OpenRead可以抛出这些异常类型。
对于每个异常类型,您都可以这样处理它。
try{
}
catch(ArgumentException e){
MessageBox.Show("ArgumentException ");
}
catch(ArgumentNullExceptione e){
MessageBox.Show("ArgumentNullExceptione");
}
.
.
.
.
catch(Exceptione e){
MessageBox.Show("Generic");
}在您的情况下,您只能处理一到两种类型,而另一种类型则总是被通用的Exception所捕获(它必须始终是lastone,因为可以排除所有异常)。
发布于 2014-12-01 11:11:05
总是从最特定的捕获到最通用的异常类型。每个异常都继承Exception-class,因此您将在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这将是分离条件的最简单的解决方案。
发布于 2014-12-01 11:12:30
尝试以下几点:
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
https://stackoverflow.com/questions/27226986
复制相似问题