【问题标题】:Filter files in a directory according to a date in the file name根据文件名中的日期过滤目录中的文件
【发布时间】:2013-05-09 05:05:26
【问题描述】:

我需要根据文件名中的日期过滤目录中的文件。

名字有四组数字:

9999.99999.201305021219.99999999.txt

当有多个文件重复第二组数字时,我想根据第三组数字 (YYYYMMDDHHMM) 上的日期使用较新的文件。

如果目录中有这些文件:

1   1100.04037.201305090945.04542592.TXT
2   1100.04041.201305091108.04542707.TXT
3   1100.04041.201305091117.60563353.TXT
4   1100.04047.201305080942.04541666.TXT
5   1100.24084.201305021658.04539125.TXT
6   1100.24084.201305061731.04540560.TXT

我希望丢弃第 2 行和第 5 行中的那些。这就是我设法遍历目录文件的方式:

    public static void Main(string[] args)
    {
        string directory = @"\\some\net\path";
        string[] arquivos = Directory.GetFiles(directory, "1100.*.txt", SearchOption.TopDirectoryOnly);
        foreach (string arquivo in arquivos)
        {
            Console.WriteLine(arquivo.Substring(directory.Length + 1));
        }
        Console.ReadLine();
    }

【问题讨论】:

  • DateTime.ParseExact 和匿名对象是你的朋友。

标签: c# list file-io filter


【解决方案1】:

根据目录中有多少文件,我建议在您遍历文件夹时使用字典来保存您的值。您可以使用第二组数字作为键,然后检查该键是否已存在于字典中。如果是,您可以执行任何适合的比较,以确定您保留哪一个。

【讨论】:

    【解决方案2】:
    var ci = CultureInfo.InvariantCulture;
    
    // first, parse your input files:
    var parsed = 
    from f in arquivos 
    let c = Path.GetFileName(f).Split('.')
    select new 
    { 
      Key = c[1], 
      Name = f, 
      Date = DateTime.ParseExact(c[2], "yyyyMMddHHmm", ci) 
    };
    
    // now, group by file id, and order by file date, 
    // picking record by latest date:
    var result = 
    parsed.GroupBy(g => g.Key)
    .Select(t => t.OrderByDescending(z => z.Date)
    .Select(z => z.Name).First()).ToList();
    

    【讨论】:

      【解决方案3】:
      var files = arquivos
                 .Select(f => new{OrgName = f, Parts = new FileInfo(f).Name.Split('.')})
                 .GroupBy(x=>x.Parts[1])
                 .Select(g=>g.OrderByDescending(x=>x.Parts[2]).First().OrgName);
      
      foreach (string arquivo in files)
      {
          .....
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多