title: C# Slow performance when copying files within network
body: <p>My implementation has 2 servers, a web server where my ASP.NET MVC project is located, an another server (AWS) where the data is. </p>
  
  <p>I have a copy routine that takes about 3 minutes to run in my local machine so I don't think there's nothing wrong with it, however when on the server it takes over 45 minutes. </p>
  
  <p>This routine is executed in the web server and accesses the AWS server over an Active Directory domain using impersonation. Both source and destination folders are within the same folder in the AWS server, so it's not copying files across the network, the copy process is done within the same folder. </p>
  
  <p>What additional operation is this routine doing so that it takes many times more to copy a folder that otherwise would only take 3 minutes to be copied across?</p>
  
  <p>This is the code I'm running:</p>
  
  <pre><code>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);
                          }
                      }
                  }
              }
          }
      }
  </code></pre>