Home  >  Article  >  Backend Development  >  How to catch file not found exception in C#?

How to catch file not found exception in C#?

王林
王林forward
2023-09-12 21:01:041377browse

How to catch file not found exception in C#?

A file not found exception is thrown when you try to find a file that does not exist.

Suppose I set a non-existent file "new.txt" in StreamReader. If you try to access it (read it) using StreamReader it will throw FileNotFoundException -

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

To handle it you need to use try and catch -

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

The above is the detailed content of How to catch file not found exception in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete