C# 处理文件错误

C# Handle file errors

我正在尝试打开一个文件,我想 return 例如X 如果文件路径不存在,Y 如果文件无法打开,Z 如果成功。

但是,我不明白如何检查“文件无法打开”错误,而且我不确定我的 try-catch 到目前为止是否正确。我还想添加另一个语句来检查文件是否已经打开。

public int Opener(string fileName)
    { 
    string text = "";
        
        try
        {
            text = File.ReadAllText(fileName);
            return "Something to Return";
        }
        catch (FileNotFoundException)
        {
            return "Something to Return";
        }

函数被声明为 return 和 int,所以你需要一个数字,比如 -1、0 或 1。如果你想 return 一个文本错误消息,将函数 return 类型更改为 string

您可以使用它来检查您描述的案例:

try
{
    string text = File.ReadAllText(fileName);

    //Z: reading was successful
}
catch (Exception ex)
{
    if (ex.InnerException is IOException)
    {
        //Y: file is already being read
    }
    else if (ex.InnerException is FileNotFoundException)
    {
        //X: file does not exist
    }
}