Mega Code Archive

 
Categories / C# / Language Basics
 

Demonstrates using if statements to sort out an IOException

/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // IOExcept.cs -- Demonstrates using if statements to sort out an IOException // //                Compile this program with the following command line: //                    C:>csc IOExcept.cs // namespace nsExcept {     using System;     using System.IO;     public class IOExcept     {         static public void Main (string [] args)         {             if (args.Length == 0)             {                 Console.WriteLine ("Please enter a file name");                 return;             }             ReadFile (args[0]);         }         static public void ReadFile (string FileName)         {             FileStream strm = null;             StreamReader reader = null;             try             {                 strm = new FileStream (FileName, FileMode.Open,                                                    FileAccess.Read);                 reader = new StreamReader (strm);                 while (reader.Peek() > 0)                 {                     string str = reader.ReadLine();                     Console.WriteLine (str);                 }             }             catch (IOException e)             {                 if (e is EndOfStreamException)                 {                     Console.WriteLine ("Attempted to read beyond end of file");                 }                 else if (e is FileNotFoundException)                 {                     Console.WriteLine ("The file name " + FileName +                                        " cannot be found");                     return;                 }                 else if (e is DirectoryNotFoundException)                 {                     Console.WriteLine ("The path for name " + FileName +                                        " cannot be found");                     return;                 }                 else if (e is FileLoadException)                 {                     Console.WriteLine ("Cannot read from " + FileName);                 }                 reader.Close();                 strm.Close ();             }             catch (Exception e)             {                 Console.WriteLine (e.Message);             }         }     } }