怎麼是這樣的:
bool MoveOldestFolder(string initialFolderName, string destinationFolder)
{
// gets all top folders in your chosen location
var directories = System.IO.Directory.EnumerateDirectories(initialFolderName,"*", System.IO.SearchOption.TopDirectoryOnly);
// stores the oldest folder and it's date at the end of algorithm
DateTime outDate;
DateTime oldestDate = DateTime.MaxValue;
string resultFolder = string.Empty;
// just a temp variable
string tmp;
// using LINQ
directories.ToList().ForEach(p =>
{
tmp = new System.IO.FileInfo(p).Name; // get the name of the current folder
if (DateTime.TryParseExact(tmp,
"yyyyMMdd", // this is case sensitive!
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out outDate)) // try using folder name as date that "should" be in yyyyMMdd format - if the conversion is successful and date is older than current outDate, then store folder name and date, else nothing
{
if (outDate.Date < oldestDate.Date)
{
oldestDate = outDate;
resultFolder = p;
}
}
});
// if we actually found a folder that is formatted in yyyyMMdd format
if (!oldestDate.Equals(DateTime.MaxValue))
{
try
{
System.IO.Directory.Move(resultFolder, destinationFolder);
return true;
}
catch(Exception ex)
{
// handle the excaption
return false;
}
}
else
{
// we didnt find anything
return false;
}
}
private void button1_Click(object sender, EventArgs e)
{
var initialFolderName = @"C:\initial";
var destinationFolder = @"c:\dest";
if (MoveOldestFolder(initialFolderName, destinationFolder))
{
// move was successful
}
else
{
// something went wrong
}
}
其他選項是簡單地做chrfin
說,但我不會在一切是在文件夾結構「花花公子」設定。文件夾名稱總是有可能不是YYYYMMDD格式,這可能會導致我想象中的一些問題。 無論如何,代碼可能看起來像這樣:
var directories = System.IO.Directory.EnumerateDirectories(initialFolderName,"*", System.IO.SearchOption.TopDirectoryOnly);
directories.ToList<string>().Sort();
var lastDir = directories.First();
「我看過......並試圖」 - 但?什麼不適合你?如果你不清楚你的問題與那個問題有什麼不同,它可能會被認爲是重複的。 – chiccodoro
我也不明白你的問題。如果文件夾名稱是'YYYYMMDD'格式,一個簡單的「字母順序」應該可以完成這項工作...... – ChrFin