簡體   English   中英

C# 處理文件錯誤

[英]C# Handle file errors

我正在嘗試打開一個文件,如果文件路徑不存在,我想返回例如 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";
        }

您可以使用它來檢查您描述的情況:

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
    }
}

function 被聲明為返回一個int ,因此您需要一個數字,例如 -1、0 或 1。如果要返回文本錯誤消息,請將 function 返回類型更改為string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM