gpt4 book ai didi

c# - 捕捉 IOException

转载 作者:行者123 更新时间:2023-11-30 16:09:40 28 4
gpt4 key购买 nike

我正在编写一个 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涵盖了这两种情况,那么如何区分这个异常是因为文件被另一个进程使用还是文件不存在而被捕获?

如有任何帮助,我们将不胜感激。

最佳答案

总是从最具体到最通用的异常类型中捕获。每个异常都继承了 Exception 类,因此您将在 catch (Exception) 语句中捕获任何异常

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

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

所以 catch Exception 总是在最后。检查 if 是可能的,但不常见。

关于您的问题:

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

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

关于c# - 捕捉 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27226986/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com