首頁  >  文章  >  後端開發  >  如何捕獲C#中的檔案未找到異常?

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

王林
王林轉載
2023-09-12 21:01:041378瀏覽

如何捕獲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);
   }

以上是如何捕獲C#中的檔案未找到異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除