【发布时间】:2016-01-17 15:09:27
【问题描述】:
我想从文件列表中按月创建文件夹。
我试过下面的代码。
var files = directory.GetFiles()
.Where(file => file.LastWriteTime.Month == date.Month -1);
//create folder for the files (With MonthName)
var year = files.Select(j => j.LastWriteTime.Year).FirstOrDefault();
var month = files.Select(j => j.LastWriteTime.Month).FirstOrDefault();
var newFolderPath = year.ToString() + month.ToString();
var destinationDirec = System.IO.Directory.CreateDirectory(directory + newFolderPath);
foreach (var f in files)
{
// var destFile = System.IO.Path.Combine(directory, destinationDirec);
var path = Path.Combine(destinationDirec.FullName, f.Name);
if (!File.Exists(path))
{
System.IO.File.Move(f.FullName, path);
}
}
上面的代码给出了上个月的文件列表。但我想为早于本月的文件创建文件夹。 谁能给我一个解决方案?
【问题讨论】:
-
您想按月份对所有文件进行排序,然后将它们放置到具有适当名称的单独文件夹中吗?
-
查找最大和最小日期并在它们之间的每个月/年迭代以创建文件夹。然后,在编写时,使用现有的
var year ...和var month来获取实际目的地。详细信息取决于您预期的日期范围。 -
@kote - 是的,你是对的。
标签: c# asp.net .net system.io.file