.NET provides a simplified and easier way of working with resources that needs to be disposed (released when we no longer need them) through construct called a Using directive. Here is an example of how we can read a filename (just like in our previous two lessons) and automatically release it when we are done dealing with it, using this keyword:
1 2 3 4 |
using (StreamReader reader = new StreamReader(fileName)) { // Use the reader variable here } |
By enclosing the declaration of our reader variable inside the using instruction, we can use it just as we normally would, but we don’t need to worry about releasing the file when we are done with it. However, if we supply a file that does not exist, we will still get a System.IO.FileNotFoundException, and that’s why we still need to wrap the Using directive in a Try Catch construct:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
using System; using System.IO; namespace HelloWorld { class Program { static void Main(string[] args) { string fileName = "NonExistantTextFile.txt"; ReadFile(fileName); Console.ReadLine(); } static void ReadFile(string fileName) { // Exceptions could be thrown in the code below try { // We can directly use declare the reader variable here using (StreamReader reader = new StreamReader(fileName)) { // And we can use it here, if the file can be read string line = reader.ReadLine(); Console.WriteLine(line); // And we know it will be disposed here } } catch (FileNotFoundException fnfe) { // Exception handler for FileNotFoundException // We just inform the user that there is no such file Console.WriteLine("The file '{0}' is not found.", fileName); } catch (IOException ioe) { // Exception handler for other input/output exceptions // We just print the stack trace on the console Console.WriteLine(ioe.StackTrace); } catch (Exception ex) { // Exception handler for any other exception that may occur and was not already handled specifically // We print the entire exception on the console Console.WriteLine(ex.ToString()); } } } } |