File Read Write Using System.IO via StreamReader and StreamWriter

February 8th, 2012 | Posted by Vidya Vrat in .NET | C# | Visual Studio

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

 

 

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.