我有一个大约30-40个文件夹的目录,其中包含CRM系统的各种备份文件。
我开发了一个从远程服务器下载文件的脚本,并将它们放在YYYYMMDD
的文件夹中,但是由于空间限制,我现在需要从目录中移动最旧的文件夹。由于公司的IT团队不断在服务器之间移动文件夹,我无法使用文件夹创建日期!
最简单的选择是什么?我查看过:deleting the oldest folder by identifying from the folder name并尝试订购商品然后执行移动。
我的另一个选择是获取根目录中的所有文件夹名称,解析为类型时间和日期列表,选择最低(最旧)选项,然后执行文件移动?
答案 0 :(得分:1)
这样的事情怎么样:
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
所说的内容,但我不会假设所有内容都是&#34; dandy&#34;在文件夹结构中。文件夹名称总是有可能不是YYYYMMDD格式,这可能会导致我想象的一些问题。
无论如何,代码看起来像这样:
var directories = System.IO.Directory.EnumerateDirectories(initialFolderName,"*", System.IO.SearchOption.TopDirectoryOnly);
directories.ToList<string>().Sort();
var lastDir = directories.First();