C# 从具有特定创建时间的目录中获取文件
C# get Files from directory with specific CreationTime
我正在编写一个简短的代码来将文件从一个目录移动到另一个目录。我的代码很简单,工作正常,看起来像这样:
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);
}
}
程序从源路径获取所有文件,并在每个文件的 foreach 循环中组合目标路径,包含目标路径和文件名。然后它移动它。一切正常。
我现在的目标是,不要将目录中的所有文件都存储到字符串数组中。我只想获取 CreationTime 在 01.07.2021 之后的文件。有什么简单快捷的方法吗?
我已经用它来获取文件,但它指定了一个单一的日期,而不是特定日期之后的所有文件:
var files = Directory.GetFiles(sourcePath).Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.Date);
如果你能帮助我,我会很高兴。
此致,
利亚姆
您可以使用 FileInfo
FileInfo fileInfo = new(s);
if (fileInfo.CreationTime >= DateTime.Parse("01/07/2021"))
{
...
}
如果您想避免检查每个 FileInfo
的创建日期,您可以订购您的文件。像这样:
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
}
这有利也有弊,订购大量文件可能比“仅仅”简单地遍历所有文件并比较日期花费更长的时间,但您需要自己对其进行基准测试
我正在编写一个简短的代码来将文件从一个目录移动到另一个目录。我的代码很简单,工作正常,看起来像这样:
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);
}
}
程序从源路径获取所有文件,并在每个文件的 foreach 循环中组合目标路径,包含目标路径和文件名。然后它移动它。一切正常。
我现在的目标是,不要将目录中的所有文件都存储到字符串数组中。我只想获取 CreationTime 在 01.07.2021 之后的文件。有什么简单快捷的方法吗?
我已经用它来获取文件,但它指定了一个单一的日期,而不是特定日期之后的所有文件:
var files = Directory.GetFiles(sourcePath).Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.Date);
如果你能帮助我,我会很高兴。
此致, 利亚姆
您可以使用 FileInfo
FileInfo fileInfo = new(s);
if (fileInfo.CreationTime >= DateTime.Parse("01/07/2021"))
{
...
}
如果您想避免检查每个 FileInfo
的创建日期,您可以订购您的文件。像这样:
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
}
这有利也有弊,订购大量文件可能比“仅仅”简单地遍历所有文件并比较日期花费更长的时间,但您需要自己对其进行基准测试