Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...