Catch file read exception and retry : Stream Read Write : File Stream C# Source Code


Custom Search

C# Source Code » File Stream » Stream Read Write »

 

Catch file read exception and retry








    
 
using System;
using System.IO;

class Retry {
    static void Main() {
        StreamReader sr;

        int attempts = 0;
        int maxAttempts = 3;

    GetFile:
        Console.Write("\n[Attempt #{0}] Specify file " + "to open/read: ", attempts + 1);
        string fileName = Console.ReadLine();

        try {
            sr = new StreamReader(fileName);
            string s;
            while (null != (s = sr.ReadLine())) {
                Console.WriteLine(s);
            }
            sr.Close();
        } catch (FileNotFoundException e) {
            Console.WriteLine(e.Message);
            if (++attempts < maxAttempts) {
                Console.Write("Do you want to select another file: ");
                string response = Console.ReadLine();
                response = response.ToUpper();
                if (response == "Y") goto GetFile;
            } else {
                Console.Write("You have exceeded the maximum retry limit ({0})", maxAttempts);
            }
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        }

    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo File Stream
» Stream Read Write