Code to write to the text file using C#

Karthikanbarasan
Posted by Karthikanbarasan under C# category on | Points: 40 | Views : 3837
FileStream fStream = new FileStream(@"D:\textfile.txt", FileMode.OpenOrCreate);
try
{
StreamWriter sWriter = new StreamWriter(fStream);
sWriter.BaseStream.Seek(0, SeekOrigin.End);
sWriter.Write("Put your text here");
}
catch(Exception ex)

{
throw ex;
}
finally
{
sWriter.Flush();
sWriter.Close();
}

Comments or Responses

Posted by: Tripati.patro on: 2/21/2011 Level:Starter | Status: [Member] | Points: 10
Hi Karthik,

Nice code illustration.
But when there is a use of Stream objects it will be good to use "Using" block to make the Stream objects automatically disposed.

using(StreamWriter sWriter = new StreamWriter(fStream))

{
sWriter.BaseStream.Seek(0, SeekOrigin.End);
sWriter.Write("Put your text here");
}

Login to post response