如何将最新文件从一个目录复制到另一个目录

时间:2013-02-26 06:21:05

标签: c# file-io

大家好我还是C#的新手,我的文件位于c:\ SourceFolder的目录中,它与日期字符串连接,格式为FileName_YYYYMMDD,看起来像 这样:

report_20130220.text,
report_20130222.text,
report_20130228.text,

我想只将具有最大日期的文件(例如报告_20130228.text)复制到另一个目录,请查看代码,但它会复制所有文件,但我不正确?

class Program
{
    static void Main(string[] args)
    {
        Program copy = new Program();
        DirectoryInfo sourcedinfo = new DirectoryInfo(@"C:\Users\Input");
        DirectoryInfo destinfo = new DirectoryInfo(@"C:\Users\Output");

        copy.CopyAll(sourcedinfo, destinfo);
        Console.Read();
    }
    public void CopyAll(DirectoryInfo source, DirectoryInfo target)
    {
        try
        {
            //check if the target directory exists
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            //copy all the files into the new directory

            foreach (FileInfo fi in source.GetFiles())
            {
                Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);

                  fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }

            Console.WriteLine("Success");
        }
        catch (IOException ie)
        {
            Console.WriteLine(ie.Message);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

我已根据创建时间对列表进行了排序并选择了它。有可能你必须检查和更改它,但只是次要的。

public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
    try
    {
        //check if the target directory exists
        if (Directory.Exists(target.FullName) == false)
        {
            Directory.CreateDirectory(target.FullName);
        }

        //copy all the files into the new directory
        // Modified from here
            DateTime latestDate = source.GetFiles().Max(x => DateTime.ParseExact(x.Name.Substring(x.Name.IndexOf('_') + 1), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture));

           FileInfo fileInfo = source.GetFiles().Single(x => x.Name == "report_" + latestDate.ToString("yyyyMMdd") + ".text");

            Console.WriteLine(@"Copying {0}\{1}", target.FullName, fileInfo.Name);

              fileInfo.CopyTo(Path.Combine(target.ToString(), fileInfo.Name), true);
        //ends here

        Console.WriteLine("Success");
    }
    catch (IOException ie)
    {
        Console.WriteLine(ie.Message);
    }
}

答案 1 :(得分:1)

选择最后的文件(如果文件名没有点或下划线,则有效):

IEnumerable<FileInfo> lastFiles = 
 source.EnumerateFiles()
       .Select(f => new {
            File = f,
            Name = f.Name.Split('_')[0],
            Date = DateTime.ParseExact(f.Name.Split('_', '.')[1], "yyyyMMdd",
                                       CultureInfo.InvariantCulture)
       })
       .GroupBy(x => x.Name)
       .Select(g => g.OrderByDescending(x => x.Date).First().File);

然后只需复制软管文件。


如果文件名可能包含点或下划线,则使用正则表达式提取名称和日期:

IEnumerable<FileInfo> lastFiles = 
 source.EnumerateFiles()
       .Select(f => {
           Match match = Regex.Match(f.Name, @"(?<name>.+)_(?<date>\d{8})\.\w+");
           return new {
              File = f,
              Name = match.Groups["name"].Value,
              Date = DateTime.ParseExact(match.Groups["date"].Value, "yyyyMMdd",
                                         CultureInfo.InvariantCulture) 
           };
        })
       .GroupBy(x => x.Name)
       .Select(g => g.OrderByDescending(x => x.Date).First().File);

答案 2 :(得分:1)

DateTime myFileDate = source.GetFiles().Max(i => DateTime.ParseExact(i.Name.Substring(7, 8), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture));
FileInfo myFile = source.GetFiles().Single(i => i.Name == "report_" + myFileDate.ToString("yyyyMMdd") + ".text");
myFile.CopyTo(Path.Combine(target.ToString(), myFile.Name), true);