i am writing a short code to move files from one directory to another. My code is simple, working fine and looks like this:
public void copy()
{
string sourcePath = @"/Users/philip/Desktop/start";
string destinationPath = @"/Users/philip/Desktop/Ziel";
string[] files = Directory.GetFiles(sourcePath)
foreach (string s in files)
{
string fileName = System.IO.Path.GetFileName(s);
string destFile = System.IO.Path.Combine(destinationPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
The Programm gets all files from the sourcepath and combines the targetpath in the foreach loop vor every file, containing of target path and filename. Then it moves it. Everything works fine.
My aim is now, not to store all files from my directory into the string array. I only want to get the files that have CreationTime after 01.07.2021. Is there an easy and quick way to do it?
I already used this to get the files, but it specifies a singular date and not all files after a specific date:
var files = Directory.GetFiles(sourcePath).Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.Date);
I would be glad if you could help me out.
Best regards, Liam
CodePudding user response:
You could use FileInfo
FileInfo fileInfo = new(s);
if (fileInfo.CreationTime >= DateTime.Parse("01/07/2021"))
{
...
}
CodePudding user response:
If you want to avoid having to check the creation date on every single FileInfo
you can order your files. Like so:
var directory = new DirectoryInfo(sourcePath);
var fileInfos = directory.GetFiles().OrderByDescending(fileInfo => fileInfo.CreationDate);
var result = new List<FileInfo>();
foreach (var fileInfo in fileInfos)
{
if (fileInfo.CreationDate >= DateTime.Today)
result.Add(fileInfo);
else
break; // We can break early, because we ordered our dates descending
// meaning every date after this one is smaller
}
This has upsides and downsides, ordering a huge collection of files could take longer than "just" simply iterating over all and comparing the dates, but you'll need to benchmark it on your own