C#:从特定日期获取所有文件并将其保存到文件夹 [英] C#: Get All Files From a Specific Date and Save It To a Folder

查看:214
本文介绍了C#:从特定日期获取所有文件并将其保存到文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以获取所有文件(在特定日期最后一次修改)并将其保存到新文件夹(具有特定日期的名称)中.

Is there a way to get all the files (last modified on a specific date), and save them into a new folder (with the name of the specific date).

示例文件:

在C里面:/

Image File     Date Modified

Image001.jpg   11/12/2012
Image002.jpg   11/12/2012
Image003.jpg   11/13/2012
Image004.jpg   11/12/2012

输出应为:

C:/20121112/

Image001.jpg
Image002.jpg
Image004.jpg  

C:/20121113

Image003.jpg

我当前正在使用以下语法:

I am currently using the syntax below:

var mydirectory = new DirectoryInfo("C:/");
DateTime from_date = DateTime.Now.AddDays(-1);
DateTime to_date = DateTime.Now;
var files = directory.GetFiles()
  .Where(file=>file.LastWriteTime >= from_date && file.LastWriteTime <= to_date);

但是我不知道如何将var文件保存到另一个文件夹名称.

But I don't how save to save var files to another folder name.

推荐答案

也许:

var files = Directory.EnumerateFiles(path, "*.jpg", SearchOption.TopDirectoryOnly)
                     .Select(fn => new FileInfo(fn));
var fileDateGroups = files.GroupBy(fi => fi.LastWriteTime.Date);
foreach (var dateGroup in fileDateGroups)
{
    string dir = Path.Combine(@"C:\", dateGroup.Key.ToString("yyyyMMdd"));
    Directory.CreateDirectory(dir);
    foreach (var file in dateGroup)
    {
        string newPath = Path.Combine(dir, file.Name);
        File.Copy(file.FullName, newPath, true);
    }
}

编辑:如果要搜索多个文件扩展名,则需要手动对其进行过滤:

Edit: If you want to search for multiple file extensions you need to filter them manually:

var allowed = new[]{ ".png", ".jpg" };
var files = Directory.EnumerateFiles(path, "*.*", SearchOption.TopDirectoryOnly)
                     .Where(fn => allowed.Contains(Path.GetExtension(fn)))
                     .Select(fn => new FileInfo(fn));

这篇关于C#:从特定日期获取所有文件并将其保存到文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆