You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何筛选目录中创建时间晚于指定日期的文件完成复制操作

实现方案

核心修改逻辑为将原筛选逻辑的相等判断替换为大于指定日期的判断,代码修改如下:

核心筛选代码

首先实例化指定的筛选日期边界:

// 定义筛选边界:2021年7月1日零点
DateTime filterDate = new DateTime(2021, 7, 1);
// 筛选创建时间晚于该边界的文件
var files = Directory.GetFiles(sourcePath).Where(x => new FileInfo(x).CreationTime > filterDate);

如果仅需要按自然日期判断、忽略具体时分秒,可调整为:

var files = Directory.GetFiles(sourcePath).Where(x => new FileInfo(x).CreationTime.Date > filterDate.Date);

补充优化建议

如果需要规避时区差异导致的筛选误差,可改用UTC时间进行判断:

DateTime filterDateUtc = new DateTime(2021, 7, 1, 0, 0, 0, DateTimeKind.Utc);
var files = Directory.GetFiles(sourcePath).Where(x => new FileInfo(x).CreationTimeUtc > filterDateUtc);

修改后完整方法

public void copy()
{
     string sourcePath = @"/Users/philip/Desktop/start";                                   
     string destinationPath = @"/Users/philip/Desktop/Ziel";
     // 定义筛选日期边界
     DateTime filterDate = new DateTime(2021, 7, 1);

     // 仅获取创建时间晚于2021年7月1日的文件
     var files = Directory.GetFiles(sourcePath).Where(x => new FileInfo(x).CreationTime > filterDate);              
            
     foreach (string s in files)                                                 
     {
          string fileName = System.IO.Path.GetFileName(s);                               
          string destFile = System.IO.Path.Combine(destinationPath, fileName);
          System.IO.File.Copy(s, destFile, true);
     }
}

内容的提问来源于stack exchange,提问作者Liam Bonactarian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:27:04