如何在C#中批量移动文件

How to bulk move files in C#

我有大约 150 万个文件要处理

我处理这些文件的方法是取我文件夹中的前 300 个文件,然后处理并将它们插入数据库,然后将这些文件移动到存档文件夹中。

此过程中的瓶颈是将文件移动到存档文件夹

我正在使用此代码移动文件

foreach (string file in Files)
{
    string OutputFileName = Path.GetFileName(file);
    string OutputBackupFile = OutputBackupFolder + OutputFileName;
    MoveWithReplace(file, OutputBackupFile);
}

private void MoveWithReplace(string sourceFileName, string destFileName)
{

    Log("In MoveWithReplace : " + sourceFileName + " to " + destFileName);
    try
    {
        //first, delete target file if exists, as File.Move() does not support overwrite
        if (File.Exists(destFileName))
        {
            File.Delete(destFileName);
        }

        File.Move(sourceFileName, destFileName);
    }
    catch (Exception ex)
    {
        Log("ERROR (MoveWithReplace): " + ex.ToString());
    }
}

我想知道是否有更快的方法来批量移动这些文件而不是一个一个地移动这些文件

或更快的移动方式?

P.S。文件大小平均为 100KB。

您可以尝试使用以下代码并行移动文件

Parallel.ForEach(Files, file => { 
  string OutputFileName = Path.GetFileName(file);
    string OutputBackupFile = OutputBackupFolder + OutputFileName;
    MoveWithReplace(file, OutputBackupFile);
});

private static void MoveWithReplace(string sourceFileName, string destFileName)
{

    Log("In MoveWithReplace : " + sourceFileName + " to " + destFileName);
    try
    {
        //first, delete target file if exists, as File.Move() does not support overwrite
        if (File.Exists(destFileName))
        {
            File.Delete(destFileName);
        }

        File.Move(sourceFileName, destFileName);
    }
    catch (Exception ex)
    {
        Log("ERROR (MoveWithReplace): " + ex.ToString());
    }
}

我没试过编译它