Faster file move method other than File.Move

前端 未结 3 2032
北恋
北恋 2021-02-09 02:39

I have a console application that is going to take about 625 days to complete. Unless there is a way to make it faster.

First off I am working in a directory that has a

3条回答
  •  忘了有多久
    2021-02-09 03:23

    You can move files in parallel and also using Directory.EnumerateFiles gives you a lazy loaded list of files (of-course I have not tested it with 4,000,000 files):

    var numberOfConcurrentMoves = 2;
    var moves = new List();
    var sourceDirectory = "source-directory";
    var destinationDirectory = "destination-directory";
    
    foreach (var filePath in Directory.EnumerateFiles(sourceDirectory))
    {
        var move = new Task(() =>
        {
            File.Move(filePath, Path.Combine(destinationDirectory, Path.GetFileName(filePath)));
    
            //UPDATE DB
        }, TaskCreationOptions.PreferFairness);
        move.Start();
    
        moves.Add(move);
    
        if (moves.Count >= numberOfConcurrentMoves)
        {
            Task.WaitAll(moves.ToArray());
            moves.Clear();
        }
    }
    
    Task.WaitAll(moves.ToArray());
    

提交回复
热议问题