我正在撰寫一個簡短的代碼,將檔案從一個目錄移動到另一個目錄。我的代碼很簡單,作業很正常,看起來像這樣:
public void copy()
{
string sourcePath = @"/Users/philip/Desktop/start"/span>;
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回圈中對每個檔案合并目標路徑,其中包含目標路徑和檔案名。然后,它移動它。一切運作正常。
我現在的目標是,不要把我目錄中的所有檔案都存盤到字串陣列中。我只想獲得創建時間在2021年7月1日之后的檔案。有什么簡單快速的方法可以做到這一點嗎?
我已經用這個方法來獲取檔案,但它指定了一個單一的日期,而不是特定日期之后的所有檔案:
var files = Directory.GetFiles(sourcePath).Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.Date) 。
如果你能幫助我,我將非常高興。
最好的問候。 Liam
uj5u.com熱心網友回復:
你可以使用FileInfo
FileInfo fileInfo = new(s)。
if (fileInfo.CreationTime >= DateTime.Parse("01/07/2021"/span>))
{
...
}
uj5u.com熱心網友回復:
如果你想避免在每一個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 (fileInfo.CreationDate >= DateTime.Today)
break; //我們可以提前中斷,因為我們將日期降序排列。
//意味著這個日期之后的每個日期都比較小。
}
這樣做有好處也有壞處,對一個巨大的檔案集合進行排序可能比 "僅僅 "簡單地迭代所有檔案并比較日期要花更多的時間,但你需要自己進行基準測驗
。轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310093.html
標籤:
