Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để chụp tệp không tìm thấy ngoại lệ trong C #?

Tệp không tìm thấy ngoại lệ được đưa ra khi bạn cố gắng tìm một tệp không tồn tại.

Giả sử tôi đã đặt một tệp trong StreamReader, “new.txt” không tồn tại. Nếu bạn cố gắng truy cập nó bằng StreamReader (để đọc nó), nó sẽ ném FileNotFoundException -

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

Để xử lý, bạn cần sử dụng try and catch -

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