遍历特定系统日期的所有文件-C#

问题描述 投票:0回答:1

我正在尝试将特定系统日期的所有文件从一个目录复制到另一个目录。但是,所有文件都将被复制,而不仅仅是指定日期。如果我们假设文件在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
1个回答
0
投票

我所看到的日期与您使用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);
            });
    }
© www.soinside.com 2019 - 2024. All rights reserved.