温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - File handling exceptions
.net c# exception file

c# - 文件处理异常

发布于 2020-04-11 14:19:51

在.NET控制台应用程序中,正在try / catch块中打开一个文件进行读取。如果文件已打开或不存在,则应向用户发出一条打印到控制台的消息提醒用户。对于每种情况,应将消息分开。如何做到这一点?如果System.IOException无法使用,则无法区分这两种情况:

try
{
    // open the file
}
catch (System.IOException)
{
    // print a message (Console.WriteLine)
}

查看更多

提问者
Al2110
被浏览
117
Anu Viswan 2020-02-02 11:40

如果您想使用Try-Catch方法,则可以使用FileNotFoundException该方法检查是否由于找不到指定的文件/路径而引发了异常

try
{
  // Attempt Opening the file
}
catch (FileNotFoundException e)
{
  // File Not Found
}
catch(IOException e) when (e.Message.Contains($"The process cannot access the file '{filePath}' because it is being used by another process"))
{
  // File being used by another process
}
catch(IOException e) 
{
  // An I/O error occurred while opening the file (could be any other reason)
}

此外,您可以过滤IOException以确保特定错误是由于文件被任何其他进程使用而引起的。

另外,您也可以File.Exists在尝试打开文件之前检查文件是否存在。

if(File.Exists(filePath))
{
   try
   {
     // File Exist, open the file
   }
   catch(IOException e)
   {
     // Error opening the file
   }
}
else
{
  // File do not exist
}