Home > Software engineering >  How to merge multiple files into one?
How to merge multiple files into one?

Time:06-23

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

CodePudding user response:

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);
}
  •  Tags:  
  • c#
  • Related