如何按照上次修改日期月份c#从文件列表创建文件夹

时间:2016-01-17 15:09:28

标签: c# asp.net .net system.io.file

我想从文件列表中按月创建文件夹。

我尝试了以下代码。

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);
                 }                  

             }               

上面的代码给出了上个月的文件列表。但我想为比当前月份更早的文件创建文件夹。 谁能给我一个解决方案?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码。也许有一些变化。

//Group files by month. Later you can skip some groups if needed
var fileGroups = directory.GetFiles()
    .GroupBy(file => file.LastWriteTime.Month);

foreach (var fileList in fileGroups)
{
    var year = fileList.First().LastWriteTime.Year;
    var month = fileList.First().LastWriteTime.Month;
    var newFolderPath = year.ToString() + month.ToString();
    var destinationDirec = System.IO.Directory.CreateDirectory(directory + newFolderPath);

    //move files
    foreach (var file in fileList)
    {
        var path = Path.Combine(destinationDirec.FullName, file.Name);
        if (!File.Exists(path))
        {
            System.IO.File.Move(file.FullName, path);
        }
    }
}

如果您有不同年份的大量文件,也许修改GroupBy条件是值得的 例如,您可以使用此条件:
GroupBy(file => (397 * file.LastWriteTime.Year) ^ file.LastWriteTime.Month)

答案 1 :(得分:0)

这应该有帮助,可以根据需要构建fullNewDir值。

String fullSourceDir = "G:\\Tmp\\Test";     
foreach (var fullFileName in Directory.EnumerateFiles(fullSourceDir)){
    DateTime lastWriteTime = File.GetLastWriteTime(Path.Combine(fullSourceDir, fullFileName));
    String fullNewDir = Path.Combine(fullSourceDir, lastWriteTime.ToString("yyyy-MM-dd_HH-mm"));
    if (!Directory.Exists(fullNewDir)){
        Directory.CreateDirectory(fullNewDir);
    }
    String fileName = Path.GetFileName(fullFileName);
    System.IO.File.Move(fullFileName, Path.Combine(fullNewDir, fileName));
}