如何在 C# 中捕獲檔案未找到異常?


嘗試查詢不存在的檔案時,將會引發檔案找不到的異常。

假設我在 StreamReader 中設定了一個不存在的檔案 “new.txt”。如果你嘗試使用 StreamReader 訪問它(讀取它),它將丟擲 FileNotFoundException -

using (StreamReader sReader = new StreamReader("new.txt")) {
sReader.ReadToEnd();
}

要處理它,你需要使用 try 和 catch -

Try {
   using (StreamReader sReader = new StreamReader("new.txt")) {
      sReader.ReadToEnd();
   }
   }catch (FileNotFoundException e) {
      Console.WriteLine("File Not Found!");
      Console.WriteLine(e);
   }

更新於:2020 年 6 月 20 日

283 次瀏覽

職業生涯起航

完成本課程即可獲得認證

開始學習
廣告