C#如何将指定日期(如15天前)的文件批量复制到另一个目录
C#复制指定日期前文件代码修复方案
核心修改逻辑如下:
- 原代码未读取文件自身的时间属性,也没有增加日期过滤规则,导致所有文件都会被复制
- 新增15天时间阈值的全局定义,删除循环内无效的时间重复赋值逻辑
- 新增文件最后修改时间校验:只有最后修改时间早于等于15天前的文件才会触发复制操作
- 新增目标目录自动创建逻辑,避免目标路径不存在时复制报错
修改后的完整代码:
using System; namespace DeleteOldLogFiles { public class Copier { public Copier() { string sourcePath = @"M:\"; string targetPath = @"L:\"; // 提前定义15天前的时间阈值,仅需计算一次 DateTime cutoffDate = DateTime.Today.AddDays(-15); if (System.IO.Directory.Exists(sourcePath)) { // 自动创建目标目录,不存在也不会报错 System.IO.Directory.CreateDirectory(targetPath); string[] files = System.IO.Directory.GetFiles(sourcePath); foreach (string s in files) { // 获取当前文件的最后修改时间 DateTime fileLastWriteTime = System.IO.File.GetLastWriteTime(s); // 仅复制最后修改时间早于等于15天前的文件 if (fileLastWriteTime <= cutoffDate) { string fileName = System.IO.Path.GetFileName(s); string destFile = System.IO.Path.Combine(targetPath, fileName); System.IO.File.Copy(s, destFile, true); } } } else { Console.WriteLine("Error, source path does not exist."); } } } }
补充说明:如果需要按文件的创建时间过滤,把GetLastWriteTime替换为GetCreationTime即可。
内容的提问来源于stack exchange,提问作者tapeworm
相关产品推荐
相关产品推荐

