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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:27:02