【问题标题】:C# Slow performance when copying files within networkC# 在网络中复制文件时性能降低
【发布时间】:2017-03-14 08:50:00
【问题描述】:

我的实现有 2 个服务器,一个是我的 ASP.NET MVC 项目所在的 Web 服务器,另一个是数据所在的服务器 (AWS)。

我有一个复制例程,在我的本地机器上运行大约需要 3 分钟,所以我认为它没有什么问题,但是在服务器上需要超过 45 分钟。

此例程在 Web 服务器中执行,并使用模拟通过 Active Directory 域访问 AWS 服务器。源文件夹和目标文件夹都在 AWS 服务器的同一个文件夹中,因此它不会通过网络复制文件,复制过程是在同一个文件夹中完成的。

这个例程做了什么额外的操作,使得复制一个文件夹需要多倍的时间,否则复制一个文件夹只需要 3 分钟?

这是我正在运行的代码:

using (new Impersonation("domain.com", "Administrator", "password"))
{
    Directory.CreateDirectory(webFolder.Replace(@"\", "\\"));
    foreach (string dirPath in Directory.GetDirectories(templatePath, "*", SearchOption.AllDirectories))
              Directory.CreateDirectory(dirPath.Replace(templatePath, webFolder));

    foreach (string newPath in Directory.GetFiles(templatePath, "*.*", SearchOption.AllDirectories))
              FCopy(newPath, newPath.Replace(templatePath, webFolder));
 } 


static void FCopy(string source, string destination)
    {
        int array_length = (int)Math.Pow(2, 10);
        byte[] dataArray = new byte[array_length];
        using (FileStream fsread = new FileStream
        (source, FileMode.Open, FileAccess.Read, FileShare.None, array_length))
        {
            using (BinaryReader bwread = new BinaryReader(fsread))
            {
                using (FileStream fswrite = new FileStream
                (destination, FileMode.Create, FileAccess.Write, FileShare.None, array_length))
                {
                    using (BinaryWriter bwwrite = new BinaryWriter(fswrite))
                    {
                        for (; ; )
                        {
                            int read = bwread.Read(dataArray, 0, array_length);
                            if (0 == read)
                                break;
                            bwwrite.Write(dataArray, 0, read);
                        }
                    }
                }
            }
        }
    }

【问题讨论】:

  • 您的意思是您的源文件夹和目标文件夹仅在 Web 服务器中?为什么不使用 File.Copy ?
  • File.Copy 出现同样的问题

标签: c# asp.net amazon-web-services copy


【解决方案1】:

源文件夹和目标文件夹都在 AWS 服务器的同一个文件夹中,然后数据也在网络中流动,因为您的数据将在您的应用程序正在执行的地方流动。我不确定这段代码中有什么好的解决方案。但是如果您可以使用可以将代码性能提高至少 1.5 倍的 powershell 脚本。脚本如下:

要获得在 powershell 命令提示符下执行 Powershell 脚本的必要访问权限,请使用以下命令,然后将数据从源复制到目标。

Set-ExecutionPolicy RemoteSigned

复制项目 -Path \serverb\c$\programs\temp\test.txt -Destination \servera\c$\programs\temp\test.txt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2011-12-14
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    相关资源
    最近更新 更多