C# How to rename MANY files faster or at the same time?

Asked

Viewed 285 times

2

So guys, I’m creating here a program to rename files, the code I’ve made is very slow and only renames one file at a time, and I can’t create a code to rename all at once because they’re different numbers and it’s not in sequence what might make it easier.

Code;

        DirectoryInfo pasta = new DirectoryInfo(folderPath);

        FileInfo[] adxs1 = pasta.GetFiles();
        foreach (FileInfo names in adxs1)
        { File.Move(names.FullName, names.FullName.ToString().Replace("old_00079", "new_00098")); }

        FileInfo[] adxs2 = pasta.GetFiles();
        foreach (FileInfo names in adxs2)
        { File.Move(names.FullName, names.FullName.ToString().Replace("old_00091", "new_00105")); }

So, the sequence is this, and are MANY files more than 1000 rsrs. What I wanted to know from you is if I can, for example, rename all or a part at once, even if they are different numbers?

  • It can if you see a pattern. I just can’t figure out why to get the files back if already caught once, and why not do everything in one loop only. Other than this, I could do asynchronously,l although 1000 should be pretty fast.

1 answer

3


You can use parallelism:

var movesSimultaneos = 2;
var moves = new List<Task>();

foreach (var filePath in Directory.EnumerateFiles(folderPath))
{
    var move = new Task(() =>
    {
        File.Move(filePath, filePath.ToString().Replace("old_00079", "new_00098"));
    }, TaskCreationOptions.PreferFairness);
    move.Start();

    moves.Add(move);

    if (moves.Count >= movesSimultaneos)
    {
        Task.WaitAll(moves.ToArray());
        moves.Clear();
    }
}

Task.WaitAll(moves.ToArray());

I translated from here.

Addendum

File.MoveTo() performs better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.