首页 > 解决方案 > 将特定日期的文件复制到另一个目录

问题描述

我是 C# 新手,我无法将 15 天前的所有文件从一个目录复制到另一个目录。这就是我所拥有的。

这只是复制类。

using System;

namespace DeleteOldLogFiles
{

    public class Copier
    {
        public Copier() 
        {
            string sourcePath = @"M:\";
            string targetPath = @"L:\"; 
            string fileName = string.Empty;
            string destFile = string.Empty;
            DateTime fileDate = DateTime.Today.AddDays(-15);


            if (System.IO.Directory.Exists(sourcePath))
            {
                string[] files = System.IO.Directory.GetFiles(sourcePath);

                foreach (string s in files)
                {

                    fileName = System.IO.Path.GetFileName(s);
                    fileDate = DateTime.Today.AddDays(-15);
                    destFile = System.IO.Path.Combine(targetPath, fileName);
                    System.IO.File.Copy(s, destFile, true);
                }
            }
            else
            {
                Console.WriteLine("Error, path does not exist.");
            }
        }
    }
}

标签: c#.net

解决方案


无法使用标准按日期搜索文件System.IO。但是,一旦您有了潜在候选人名单,就会有. 选择适合您需要的时间戳,将其与您的日期限制变量进行比较,并根据比较结果执行/不执行复制。File.GetLastWriteTime() File.GetLastAccessTime() File.GetCreationTime()

不完全清楚,你的意思是什么

复制 15 天前的所有文件

例如,如果您想复制过去 15 天内创建的所有文件,您可以执行以下操作:

var limit = DateTime.Today.AddDays(-15);
foreach (string s in files)
{
  var creationTime = System.IO.File.GetCreationTime(s);
  if (creationTime > limit) {  //the file was created within the last 15 days
    string fileName = System.IO.Path.GetFileName(s);
    string destFile = System.IO.Path.Combine(targetPath, fileName);
    System.IO.File.Copy(s, destFile, true);
  }
}

如果您有其他意思,请相应地调整比较。

此外,无需在循环体之外定义fileNameor变量。destFile

此外,您可能需要重新考虑在类构造函数中执行此操作。似乎这个类的唯一目的是复制文件,一旦复制完成,就不需要该类的实例。也许一个static方法会更好......


推荐阅读