Friday, March 30, 2007

C#: writing to text file

using System;
using System.IO;

namespace FileIOText
{
class WriteTextFile
{
public WriteTextFile()
{
try
{
//-- "using" also closes the file
using (StreamWriter sw = new StreamWriter("data.txt"))
{
sw.Write("Hello...");
sw.WriteLine("This is the start of the writing...");
sw.WriteLine("------------------");
//-- write arbitrary objects
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
}
}
catch (Exception e)
{
Console.WriteLine("File could not be written");
Console.WriteLine(e.Message);
}
}
}
}

No comments: