Home > Article > Backend Development > 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!