在 c# 中附加多个 CSV [已关闭]

问题描述 投票:0回答:1

我在一个文件夹中生成多个 CSV,我必须将它们全部合并并创建一个文件。

P.s. 1.它们都有相同的标题。 2.他们的名字不是固定的,会根据日期和其他一些参数每隔一天更改一次。

c# csv merge
1个回答
1
投票

未经真正测试,但应该给你一个想法:

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

请注意,您必须添加

using  System.Linq;

© www.soinside.com 2019 - 2024. All rights reserved.