File read exception handling

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);
        }
 
 
    }
}

Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

Filed Under: C# Streams Examples

RSSComments (0)

Trackback URL

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.