【问题标题】:Looping through all the files for specific system date - C#循环遍历特定系统日期的所有文件 - C#
【发布时间】:2020-02-25 03:28:43
【问题描述】:

我正在尝试将特定系统日期的所有文件从一个目录复制到另一个目录。但是,所有文件都会被复制,而不仅仅是指定日期。 如果我们假设文件在c:\testfiles\

Date_Modified            Name 
2/14/2020 5:00 AM        txt_1.csv
2/14/2020 5:30 AM        txt_2.csv 
2/14/2020 6:00 AM        txt_3.csv 
2/13/2020 6:00 AM        txt_4.csv 
2/13/2020 6:15 AM        txt_5.csv 

下面的代码应该获取最近的日期,也就是这里的2/14/2020,并仅循环遍历2/14 的文件。但是这段代码也可以获取2/13 文件。

// this gives me the latest date.
DateTime dt = File.GetLastWriteTime(LatestFile);
DateTime dateonly = dt.Date;

// this is the code which I assumed would loop through only 2/14, but it is looping through all files. 
 var latestFiles = Directory.GetFiles(sourcepath).Where(x => new FileInfo(x).CreationTime.Date == dt.Date);
                foreach (string s in latestFiles)
                {

                     string destfile = targetPath + System.IO.Path.GetFileName(s);
                     System.IO.File.Copy(s, destfile, true);
                }

如何仅将 2/14 的文件复制到另一个目录?我必须查找最近的日期并将该日期的所有文件复制到另一个目录中。

我错过了什么?

【问题讨论】:

  • 您确定不要LastWriteTime 而不是CreationTime
  • Date_Modified != CreationTime
  • @Enigmativity.. 我想在一个目录中获取最新日期的所有文件.. 我对 c# 很陌生,不确定使用哪个。
  • 所有文件都有 3 个日期(创建、访问、写入dir 命令术语),您可以使用dir * /t:Cdir * /t:Adir * /t:W 查看)。查看该信息并弄清楚“最新日期”是什么意思 - edit 随后发帖澄清。

标签: c# fileinfo


【解决方案1】:

我可以看到您正在使用 GetLastWriteTime 并与 CreationTime 比较的最新文件的日期不同

static void Main(string[] args)
    {
        var path = "c:/test"; //Create the directory with some files
        var latestFile = "c:/test/test2.txt"; // Name of one file which is in c:/test
        var targetPath = "c:/test2"; //Create the directory

        Directory.GetFiles(path)
            .Where(e => File.GetLastWriteTime(e).Date.Equals(File.GetLastWriteTime(latestFile).Date))
            .ToList()
            .ForEach(e =>
            {
                Console.WriteLine($"Copying {e}");
                File.Copy(e, Path.Join(targetPath, Path.GetFileName(e)), true);
            });
    }

【讨论】:

    猜你喜欢
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    相关资源
    最近更新 更多