Read a file and catch all exceptions - CSharp Custom Type

CSharp examples for Custom Type:Exception

Description

Read a file and catch all exceptions

Demo Code

using System;//from   w w w . j  a  v a2 s .  c  om
using System.IO;
class Program
{
   static void Main(string[] args)
   {
      try
      {
         using (StreamReader reader = new StreamReader("test-file.txt"))
         {
            string contents = reader.ReadToEnd();
            Console.WriteLine("File contents:");
            Console.WriteLine(contents);
         }
      }
      catch(FileNotFoundException e)
      {
         Console.WriteLine("File not found");
      }
      catch(FileLoadException e)
      {
         Console.WriteLine("File load failed");
      }
      catch(Exception)
      {
         Console.WriteLine("File operation failed");
      }
   }
}

Related Tutorials