首页 > 解决方案 > 将文件移动到子文件夹(每个子文件夹中有 n 个文件)

问题描述

我有一个小问题要解决。我有一个包含很多文件的文件夹。我希望它以这样一种方式将它隔离到子文件夹中,即每个子文件夹都包含一定数量的文件。例如。我有 1500 个文件,我想将其移动到 15 个子文件夹(每个文件夹中有 100 个文件)。子文件夹的名称是 wahtever 这不是问题。我不知道如何使用数组来移动它,我不知道。

我从该文件夹中读取了一个文件列表并创建了一个这样的数组:

string path = @"E:\test_folder";
string path2 = @"E:\test_folder\1";

string[] files_array = Directory.GetFiles(path);

然后我可以像这样移动文件:

foreach (file in files_array){

     File.Move(System.IO.Path.Combine(path, file), System.IO.Path.Combine(path2, file));

}

但是我如何自动创建文件夹并仅移动一定数量的文件然后创建新文件夹等。我尝试这样做,但是我必须刷新我的数组,所以我认为这不是一个好主意。

while (files_array.Lenght > 0){

    foreach (file in files_array.Take(50)){

     File.Move(System.IO.Path.Combine(path, file), System.IO.Path.Combine(path2, file));
}
string[] files_array = Directory.GetFiles(path);}

我还考虑将所有数组写入 txt 临时文件,然后逐行读取并移动文件(这样我就不必刷新数组),但我不知道该怎么做。什么是最好的解决方案?

标签: c#.net

解决方案


因此,您知道如何移动文件(使用File.Move(..)),您所需要的只是批量遍历文件名数组。一种方法是Skip/ Take

var i = 0;
var batchSize = 50;
var iterationsCount = files_array / batchSize + 1;

while (i < iterationsCount)
{
    var batch = files_array.Skip(i * batchSize).Take(batchSize);
    // do something with this batch...
}

但这完全无效。您将files_array无缘无故地在每个循环中运行一部分。


另一种方法是为这样的方法创建一个扩展方法IEnumerable<T>

public static class IEnumerableExtension
{
    public static IEnumerable<IEnumerable<T>> InBatches<T>(this IEnumerable<T> enumerable, int batchSize)
    {
        var batch = new List<T>(batchSize);
        var i = 0;

        foreach (var item in enumerable)
        {
            batch.Add(item);
            if (++i == batchSize)
            {
                // our batch is complete - yield return and create a new one
                yield return batch;
                batch = new List<T>(batchSize);
                i = 0;
            }
        }

        // something left in batch
        if (i != 0)
            yield return batch;
    }
}

现在您可以通过这种方式使用扩展:

foreach (var batch in files_array.InBatches(50))
{
    // do something with this batch...
}

推荐阅读