How to merge multiple files into one?

I wrote a code that should read all the files in the directory and save to one. Well, for some reason it only reads one file.

 foreach (var file in Directory.GetFiles(directory, "*.*"))
        {
            foreach (var line in File.ReadAllText(file))
            {
                File.WriteAllText(@"D:\ee.txt", line.ToString());
            }
        }

>Solution :

A simple way of finding the files in a Directory and merging the content into 1 new file is explained here.

string contents = string.Empty;
string[] arr = Directory.GetFiles(@"C:\Jay", "*.txt");
foreach (string file in arr)
{
   contents = File.ReadAllText(file);
   File.AppendAllText(@"C:\Jay\mergedfile.txt", contents, Encoding.Default);
}

Leave a Reply