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:

  1. Read directory and get filenames. Add names to array of string
  2. Loop through array of filenames, read contents of files and add it to string collection List<string> stringList
  3. Join string collection List<string> to a string variable
  4. 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);
            }

        }
    }
}

joinedFiles




No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment





MarkiMarta.com. Notes of web-specialist
Since 2009
18+