在.NET控制台应用程序中,正在try / catch块中打开一个文件进行读取。如果文件已打开或不存在,则应向用户发出一条打印到控制台的消息提醒用户。对于每种情况,应将消息分开。如何做到这一点?如果System.IOException
无法使用,则无法区分这两种情况:
try
{
// open the file
}
catch (System.IOException)
{
// print a message (Console.WriteLine)
}
如果您想使用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
}