如何在 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);
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP