C#复制用户定义的文件数

时间:2016-02-06 15:54:58

标签: c# file copy

我正在尝试将一定数量的文件从一个目录复制到另一个目录。我当前状态的代码复制目录中的所有文件。我相信我需要一个列表或一个数组,但对C#来说有点新,所以想在这里提出我的问题。一个例子是从代码中指定的目录中复制20个文件。任何帮助,将不胜感激。谢谢!

static void Main(string[] args)
{
}
private void CopyFiles(int numberOfFiles)
    {
        List<string> files = System.IO.Directory.GetFiles(@"C:\Users\acars\Desktop\A", "*").ToList();
        IEnumerable<string> filesToCopy = files.Where(file => file.Contains("Test_Test")).Take(20);

        foreach (string file in filesToCopy)
        {
            // here we set the destination string with the file name
            string destfile = @"C:\Users\acars\Desktop\B\" + System.IO.Path.GetFileName(file);
            // now we copy the file to that destination
            System.IO.File.Copy(file, destfile, true);
        };

2 个答案:

答案 0 :(得分:0)

通过一些修改,您的代码可以复制给定数量的文件。以下示例从您的目录中获取前x个文件:

    private void CopyFiles(int numberOfFiles)
        {
            List<string> files = System.IO.Directory.GetFiles(@"C:\Users\rando\Desktop\A", "*").ToList();
            IEnumerable<string> filesToCopy = files.Where(file => file.Contains("Test_Test")).Take(numberOfFiles);

            foreach (string file in filesToCopy)
            {
                // here we set the destination string with the file name
                string destfile = @"C:\Users\rando\Desktop\B\" + System.IO.Path.GetFileName(file);
                // now we copy the file to that destination
                System.IO.File.Copy(file, destfile, true);
            }
        }

如果您想根据特殊订单购买前x个文件,则必须先订购“文件”列表。

答案 1 :(得分:0)

Since you need to order by information about the file beyond the name, you'll need to use FileInfo. Here's what I believe to be a straightforward implementation that should get you started.

static void Main(string[] args)
{
    var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    var path = Path.Combine(desktop, "A");
    var outPath = Path.Combine(desktop, "B");

    Copy(20, "file", path, outPath, x => x.LastWriteTimeUtc);
}

static void Copy<T>(int count, string filter, string inputPath, string outputPath, Func<FileInfo, T> order)
{
    new DirectoryInfo(inputPath).GetFiles()
        .OrderBy(order)
        .Where(file => file.Name.Contains(filter))
        .Take(count)
        .ToList()
        .ForEach(file => File.Copy(file.FullName, Path.Combine(outputPath, file.Name), true));
}

To use this, you would pass in the number to copy, the paths, a filter, and an ordering action.

  • new DirectoryInfo(inputPath).GetFiles() - Get a FileInfo[] of every file in the specified path
  • .OrderBy(order) - order them
  • .Where(file => file.Name.Contains(filter)) - filter by the passed in filter
  • .Take(count) - take the count
  • .ToList() - convert to List to use ForEach
  • .ForEach(file => File.Copy(file.FullName, Path.Combine(outputPath, file.Name), true)) - Make the File.Copy() call for each