首页 > 解决方案 > 循环遍历特定系统日期的所有文件 - C#

问题描述

我正在尝试将特定系统日期的所有文件从一个目录复制到另一个目录。但是,所有文件都会被复制,而不仅仅是指定日期。如果我们假设文件在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 的文件复制到另一个目录?我必须查找最近的日期并将该日期的所有文件复制到另一个目录中。

我错过了什么?

标签: c#fileinfo

解决方案


我可以看到您正在使用 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);
            });
    }

推荐阅读