0

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.

Dark Knight
  • 125
  • 2
  • 10
  • 1
    You will have to write code. The easiest way is to google the code. There are high chances that you will get the exact code you need. – Raghu Aug 27 '14 at 10:08

1 Answers1

1

Not really tested but should give you an idea:

var allCsv = Directory.EnumerateFiles("Src-Path", ".*csv", SearchOption.TopDirectoryOnly);
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;

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Hi,i am using 3.5 framework so unable to use concat and readlines,what else i can use in place of this? p.s. not very much familiar with the c# – Dark Knight Aug 27 '14 at 13:52
  • @user3686917: you can use LINQ with .NET 3.5, but you cannot use the overload of `WriteAllLInes` which accepts an `IEnumerable`, you have to use the `string[]`. Therefore use `File.WriteAllLines("Dest-Path", header.Concat(mergedData).ToArray());` – Tim Schmelter Aug 27 '14 at 13:56
  • But you're right, `File.ReadLines` and `Directory.EnumerateFiles` were also new in .NET 4 so you need `File.ReadAllLines` and `Directory.GetFiles` which are less efficient in terms of memory consumption. – Tim Schmelter Aug 27 '14 at 13:59
  • WriteallLines i dont think will create any problem in 3.5,if we use it like File.WritAllLines("Destpath",header.Concat(mergedData.ToArray())) ,correct me if i m wrong – Dark Knight Aug 27 '14 at 14:10
  • @user3686917: no problem, have a look at my second to last comment ;-) – Tim Schmelter Aug 27 '14 at 14:12
  • need your help for this [link](http://stackoverflow.com/questions/25790667/print-excel-generated-using-spreadsheetgear-in-c-sharp) – Dark Knight Sep 11 '14 at 14:56
  • This works but with a minor tweak to use "*.csv" instead of ".*csv" in the search pattern. – Rahul Vijay Dawda Nov 30 '20 at 05:28