Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c# - Aggregating different file 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...