Search code examples
c#csvmerge

Appending multiple CSV's in c#


I am generating multiple CSV's in a folder ,I have to merge all of them and make one file.

P.s. 1.They all will have same headers. 2.Their names are not fixed and will be changed every other day acc to date and some other parameters.


Solution

  • Not really tested but should give you an idea:

    var allCsv = Directory.EnumerateFiles("Src-Path", "*.csv", SearchOption.TopDirectoryOnly); //Enumeration of the top directory
    string[] header = { File.ReadLines(allCsv.First()).First(l => !string.IsNullOrWhiteSpace(l)) };
    var mergedData = allCsv
        .SelectMany(csv => File.ReadLines(csv)
            .SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1));// skip header of each file     
    File.WriteAllLines("Dest-Path", header.Concat(mergedData));
    

    Note that you have to add using System.Linq;