Tuesday, February 07, 2012

File Read Write using System.IO via StreamReader and StreamWriter

using System;
using System.IO;
namespace FileRead_ExceptionHandling
{
    class Program
    {
        static void Main(string[] args) 
        {
            // declaring stream-reader here so it become accessible to the
            // code blocks of try { } and finally { }

           StreamReader sr = null;                      
            try
           {
                  // this assume you will have a file on C:\ as mentioned below
                  sr = new StreamReader(@"c:\TestCode2.log");
                  string text = sr.ReadToEnd();

                  Console.WriteLine(text);
           }           
          
           catch (FileNotFoundException ex)
           {
               Console.WriteLine(ex.Message + "\n
               The wrong file name or path is provided!! Try Again");
           }
           catch (Exception ex)
           {
               Console.WriteLine("Try again" + ex.Message);
           }
          
            finally
            {
                if (sr != null)
                {
                   sr.Close();
                Console.WriteLine("Stream closed");
                }
                else
                {
                   Console.WriteLine("Stearm is Null");
                   Console.WriteLine("Try Again");
                }

               // Performing stream-write operation to the same file
               StreamWriter sw = new StreamWriter(@"c:\TestCode.log", true);
               sw.WriteLine("Line 1");
               sw.Close();   

               Console.ReadLine();
              }
        }
    }
}

No comments:

Post a Comment