聚合不同的文件CSV [英] Aggregating different file CSV

查看:52
本文介绍了聚合不同的文件CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的初学者,我不了解API的详细信息。
我想编写一个.csv文件,其中包含每个文件中的单日,并包含每个文件中的数据。

I'm beginner in C# and I don't know the API in details. I would like to write a one .csv that contains a single day from each of those files, and contains the data that was there in each file.

推荐答案

您必须在C#3.0中使用普通循环,您可以填充字典例如:

You have to use plain loops in C#3.0, you could fill a Dictionary for example:

string dir = @"C:\DirectoryName";
string[] files = Directory.GetFiles(dir, "*.csv", SearchOption.TopDirectoryOnly);
var dateFiles = new Dictionary<DateTime, List<string>>();

foreach (string file in files)
{
    string fn = Path.GetFileNameWithoutExtension(file);
    if (fn.Length < "yyyyMMdd_HHmmss".Length)
        continue;
    string datePart = fn.Remove("yyyyMMdd".Length); // we need only date
    DateTime date;
    if (DateTime.TryParseExact(datePart, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out date))
    {
        bool containsDate = dateFiles.ContainsKey(date);
        if (!containsDate) dateFiles.Add(date, new List<string>());
        dateFiles[date].Add(file);
    }
}

foreach(KeyValuePair<DateTime, List<string>> dateFile in dateFiles)
    MergeFilesForDay(dir, dateFile.Key, dateFile.Value);

这是创建新文件的方法:

and here's a method that creates the new files:

static void MergeFilesForDay(string dir, DateTime date, List<string> files)
{ 
    string file = Path.Combine(dir, date.ToString("yyyyMMdd") + ".csv");
    using(var stream = File.CreateText(file))
    {
        foreach(string fn in files)
            foreach(string line in File.ReadAllLines(fn))
                stream.WriteLine(line);
    }
}

这篇关于聚合不同的文件CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆