首页 > 解决方案 > C# 复制具有指定日期和时间范围的文件

问题描述

在 Visual C# 中:

我希望将指定日期和时间范围的文件列表从一个文件夹复制到另一个文件夹。我不断获取所有文件,而不仅仅是我想要的文件。

例如:

2019 年 2 月 20 日凌晨 2 点至 2019 年 3 月 2 日凌晨 1 点(基于日期时间修改)

复制

D:\Data\SubFolder1\SubFolder2\SubFolder3\\*.log

E:\MyLogs\D\Data\SubFolder1\SubFolder2\SubFolder3\

我应该看什么函数或库?

标签: c#datetimedirectory-structure

解决方案


您可以尝试如下代码

从中导入System.IO使用DirectoryInfo

我也正在从中导入System.Linq使用Where方法。

假设您将目录路径放在变量中说yourDirectoryPath

// Specify the directory you want to use
DirectoryInfo directory = new DirectoryInfo(yourDirectoryPath);
// Check if your directory exists and only then proceed further
if (directory.Exists){
    //You would be having your fromdate and toDate in two variables like fromDate, toDate
    // files variable below will have all the files that has been lastWritten between the given range
    var files = directory.GetFiles()
                 .Where(file=>file.LastWriteTime >= fromDate && file.LastWriteTime <= toDate);
 }

现在您可以使用您现有的代码(如果您没有,请告诉我)将文件夹中的所有文件复制到目标位置。


推荐阅读