C#. Join (merge) some text files into one
The task. We have 3 separated text files, for example, web server logs. For more comfortable analyze we want to join them into one file. Below my simple solution for this task in C#.
The main steps of script are:
- Read directory and get filenames. Add names to array of string
- Loop through array of filenames, read contents of files and add it to string collection List<string> stringList
- Join string collection List<string> to a string variable
- Write result to textFile
Full code of console application below. It's the simple version. You may add more features to a code if you want to.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace splitFiles
{
class Program
{
static void Main(string[] args)
{
List<string> stringList = new List<string>();
//Get filenames from directory
string[] files = Directory.GetFiles(@"C:\Projects\splitFiles\splitFiles\filesDirectory\");
//loop through array of files, read their contents and add to collection List<string> stringList
foreach(string file in files) {
stringList.Add(System.IO.File.ReadAllText(file));
}
//Join to one string variable List<string> values
string resultText = string.Join("", stringList.ToArray());
//Write result to textFile
using (StreamWriter outFile = new StreamWriter(@"C:\Projects\splitFiles\splitFiles\filesDirectory\result.txt"))
{
outFile.Write(resultText);
}
}
}
}


C#. Best practice for OleDBConnection
How easily write the text of connection string