通过LastWriteTime复制文件

时间:2014-03-26 12:46:41

标签: c#

我打了一堵砖墙!我的目标是仅在给定的一天在两个文件夹之间复制文件,忽略与早期LastWriteTime相同的文件夹中的文件。我的逻辑似乎有效,但是我在运行代码时收到一个异常,说它无法找到我的测试文件,即使它不能告诉我我的测试文件的名称,如果它没有工作!! :(我已经在下面发布了我的代码,请帮忙!

namespace RunAfterFirstScan
{
    class Program
    {

    public static IEnumerable<string> GetNewest(string path)
    {
        DateTime to_date = DateTime.Today.AddDays(-5);
        var directoryInfo = new DirectoryInfo(path);
        if (!directoryInfo.Exists) return Enumerable.Empty<string>();

        var query =
            from file in directoryInfo.GetFiles()
            where file.LastWriteTime.Date == to_date.Date          
            select file.Name;

        return query;
    }


    static void Main(string[] args)
    {

        string sourcePath = @"C:\Users\berryn01\Desktop\From\";
        string targetPath = @"C:\Users\berryn01\Desktop\To\";

        if (!System.IO.Directory.Exists(targetPath))
        {
            System.IO.Directory.CreateDirectory(targetPath);
        }


        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = GetNewest(sourcePath).ToArray();
            foreach (string s in files)
            {

                string fileName = System.IO.Path.GetFileName(s);
                string destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile);
            }
        }
        else
        {
            Console.WriteLine("Source path does not exist!");
        }


        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();

    }
}
}

1 个答案:

答案 0 :(得分:0)

您的查询错误。我认为根据您的需要,它必须是>=<=

var query =
            from file in directoryInfo.GetFiles()
            where file.LastWriteTime.Date <= to_date.Date
            select file.Name;

var query =
            from file in directoryInfo.GetFiles()
            where file.LastWriteTime.Date >= to_date.Date
            select file.Name;