c# - 循环遍历特定系统日期的所有文件 - C#
问题描述
我正在尝试将特定系统日期的所有文件从一个目录复制到另一个目录。但是,所有文件都会被复制,而不仅仅是指定日期。如果我们假设文件在c:\testfiles\
Date_Modified Name
2/14/2020 5:00 AM txt_1.csv
2/14/2020 5:30 AM txt_2.csv
2/14/2020 6:00 AM txt_3.csv
2/13/2020 6:00 AM txt_4.csv
2/13/2020 6:15 AM txt_5.csv
下面的代码应该获取最近的日期,也就是2/14/2020
在这里,并且只循环遍历文件2/14
。但是这段代码也在拾取2/13
文件。
// this gives me the latest date.
DateTime dt = File.GetLastWriteTime(LatestFile);
DateTime dateonly = dt.Date;
// this is the code which I assumed would loop through only 2/14, but it is looping through all files.
var latestFiles = Directory.GetFiles(sourcepath).Where(x => new FileInfo(x).CreationTime.Date == dt.Date);
foreach (string s in latestFiles)
{
string destfile = targetPath + System.IO.Path.GetFileName(s);
System.IO.File.Copy(s, destfile, true);
}
如何仅将 2/14 的文件复制到另一个目录?我必须查找最近的日期并将该日期的所有文件复制到另一个目录中。
我错过了什么?
解决方案
我可以看到您正在使用 GetLastWriteTime 并与 CreationTime 比较的最新文件的日期不同
static void Main(string[] args)
{
var path = "c:/test"; //Create the directory with some files
var latestFile = "c:/test/test2.txt"; // Name of one file which is in c:/test
var targetPath = "c:/test2"; //Create the directory
Directory.GetFiles(path)
.Where(e => File.GetLastWriteTime(e).Date.Equals(File.GetLastWriteTime(latestFile).Date))
.ToList()
.ForEach(e =>
{
Console.WriteLine($"Copying {e}");
File.Copy(e, Path.Join(targetPath, Path.GetFileName(e)), true);
});
}
推荐阅读
- ruby-on-rails - 如何找到相同的记录并为每个导轨执行操作
- php - CURL 帖子表单不起作用
- java - 在现有 csv 文件中添加新列
- angular - Angular2 Material Snackbar - 如何包含 html
- javascript - 加载其他 div 元素时,如何让我的 JS 重新加载?
- java - 如何使用 maven/junit/spock 报告测试结果并按功能编号对其进行分组?
- python - python将包含日期时间对象的记录插入mysql db的问题
- ios - AVAssetWriter - 未知错误代码=-16351
- oracle - 在 CentOS 7 上安装 unixODBC 失败:libodbcinst.so.1 => not found
- json - Ionic and angular - 向服务器发送 http 请求并接收 JSON 数据,这适用于 Ionic 服务,但不适用于 Ionic Cordova 运行 Android