Home   Cover Cover Cover Cover
 

Exceptions when opening a file

/csbook/solutions/12/A03.cs
using System;
using System.IO;
using System.Security;

class Test {
  
  static void Main(string[] arg) {
    try {
      FileStream s = new FileStream(arg[0], FileMode.Open);
      StreamReader r = new StreamReader(s);
      int ch = r.Read();
      while (ch >= 0) {
        // process ch ...
        ch = r.Read();
      }
      r.Close();
      s.Close();
    } catch (ArgumentNullException) {
      Console.WriteLine("-- file name is null");
    } catch (ArgumentOutOfRangeException) {
      Console.WriteLine("-- 'mode' parameter holds an ivalid value");
    } catch (ArgumentException) {
      Console.WriteLine("-- file name is empty");
    } catch (SecurityException) {
      Console.WriteLine("-- this program does not have the required permission");
    } catch (FileNotFoundException e) {
      Console.WriteLine("-- file {0} not found", e.FileName);
    } catch (DirectoryNotFoundException) {
      Console.WriteLine("-- the directory path is invalid");
    } catch (PathTooLongException) {
      Console.WriteLine("-- path name or file name too long");
    } catch (IOException) {
      Console.WriteLine("-- some IO error occurred");
    }
  }
  
}