c# - 将特定日期的文件复制到另一个目录
问题描述
我是 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.");
}
}
}
}
解决方案
无法使用标准按日期搜索文件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);
}
}
如果您有其他意思,请相应地调整比较。
此外,无需在循环体之外定义fileName
or变量。destFile
此外,您可能需要重新考虑在类构造函数中执行此操作。似乎这个类的唯一目的是复制文件,一旦复制完成,就不需要该类的实例。也许一个static
方法会更好......
推荐阅读
- python - 有人可以帮我理解这个关于类变量与实例变量的代码片段吗?
- c# - 从 GitHub https://github.com/dotnet/wpf 构建的 .Net Core 3.1 WPF 存储库
- video - 合并视频文件和字幕
- java - FXML:未指定控制器,而控制器在控制器中指定
- ios - 即使在关闭时如何加载 JSON tableView 并保存数据?
- architecture - 网站后端架构的设计工具
- ios - UITableViewDataSource 没有返回它应该返回的行数
- java - 如何在以泛型数组作为参数的泛型方法中实现 compareTo?
- go - 尝试在 go 中创建可重用的附加到结构
- python - For Loop 每 5 分钟执行一次,持续 24 小时