Tuesday, June 13, 2006

Appending data from different text files to single file !!

These dayz I m doing nothing, except reading the code and tryin to understand it.
My senior came to me and asked me to write a small application to read all the text files from the directory and append their data into a file. Its a very small and easy thing to do, but still I m posting it thinking that this small piece of code will help someone.

using System.IO;
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo dir1 = new DirectoryInfo(@"C:\abc");

FileInfo[] txtfiles = dir1.GetFiles("*.txt");

FileInfo fxists = new FileInfo(@"c:\abc\c.txt");
if (fxists.Exists)
{
fxists.Delete();
}

foreach (FileInfo f in txtfiles)
{
StreamReader sr = File.OpenText(f.Name);
string read = null;
while ((read = sr.ReadLine()) != null)
{

FileInfo fi = new FileInfo(@"c:\abc\c.txt");
StreamWriter sw = fi.AppendText();

sw.Write(read.ToString());
sw.Close();

}

}

}