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:osI'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:osYou 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);
}
}