C# 复制具有指定日期和时间范围的文件

C# Copy file with specify date and time range

在 Visual C# 中:

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

例如:

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

复制

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

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

我应该查看什么函数或库?

您可以试试下面的代码

导入 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);
 }

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

您首先需要过滤指定时间段内 modified/created 的文件。您可以按照以下方式进行。

var directory = new DirectoryInfo(sourceFolder);
var listOfFilesInSpecifiedPeriod = directory.GetFiles("SubFolder3*.log")
                    .Where(file=>file.LastWriteTime >= fromDate && file.LastWriteTime <= endDate);

然后,您可以迭代结果以将它们复制到目标文件夹。

  foreach(var file in listOfFilesInSpecifiedPeriod)
  {
    File.Copy(file.FullName,Path.Combine(destinationFolder,file.Name));
  }

请注意,要使代码完整,您需要添加检查以确保源文件夹和目标文件夹存在。我留给你完成。