提取大于datetime.now的文件内容

时间:2018-02-28 14:40:04

标签: c# file

我有一个包含以下内容的文件,

2018-02-28 10:00:00,A1, A2 2018-02-28 10:05:00,A3, A4 2018-02-28 10:10:00,A5, A6 2018-02-28 10:00:00,A7, A8

现在我想从日期/时间大于2018-02-28 10:05:00获取所有文件内容(作为不同的文件)?

我可以在某些数据后检查修改后的文件,

var files = directory.GetFiles().Where(file=>file.LastWriteTime >= datetine.now);

但如何获取内容?

2 个答案:

答案 0 :(得分:2)

您可以使用此功能(使用C#7输出变量功能):

var fileContents = directory.GetFiles()
    .Select(f => new
    {
        File = f,
        Content = File.ReadLines(f.FullName)
                    .Select(l => new{ Line = l, Fields = l.Split(',') })
                    .Select(x => new
            {
                x.Line, x.Fields,
                DateStr = x.Fields[0].Trim(),
                IsValid = DateTime.TryParse(x.Fields[0].Trim(), out var date),
                Date = date
            })
            .Where(x => x.IsValid && x.Date > DateTime.Now)
            .ToArray()
    });

答案 1 :(得分:1)

尝试以下

           string input = "2018-02-28 10:00:00,A1, A2\n" +
                          "2018-02-28 10:05:00,A3, A4\n" +
                          "2018-02-28 10:10:00,A5, A6\n" +
                          "2018-02-28 10:00:00,A7, A8";

           DateTime now = DateTime.Now;
           var results = input.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
               .Select(x => x.Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries))
               .Select( y => new { date = DateTime.Parse(y.First()), colA = y.Skip(1).First(), colB = y.Last() })
               .Where(x => x.date <= now).ToList();