C#复制文件,指定日期和时间范围

问题描述 投票:0回答:2

在Visual C#中:

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

E.g:

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

复制

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

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

我应该看什么功能或库?

c# datetime directory-structure
2个回答
2
投票

您可以尝试以下代码

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

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


0
投票

您首先需要过滤在指定时间段内修改/创建的文件。你可以这样做。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.