首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在C#中批量移动文件

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

Stack Overflow用户
提问于 2021-05-17 05:44:58
回答 1查看 67关注 0票数 0

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

我通过将文件夹中的前300个文件放入数据库来处理这些文件,然后将它们处理并插入到数据库中,然后将这些文件移动到存档文件夹中。

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

我正在使用这段代码来移动文件

代码语言:javascript
运行
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-17 06:13:44

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

代码语言:javascript
运行
复制
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());
    }
}

我没有尝试过编译它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67561823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档