title: File.Copy in Parallel.ForEach
body: <p>I'm trying to create a directory and copy a file (pdf) inside a <code>Parallel.ForEach</code>.</p>
  
  <p>Below is a simple example:</p>
  
  <pre><code>    private static void CreateFolderAndCopyFile(int index)
      {
          const string sourcePdfPath = "c:\\testdata\\test.pdf";
          const string rootPath = "c:\\testdata";
  
          string folderDirName = string.Format("Data{0}", string.Format("{0:00000000}", index));
  
          string folderDirPath = rootPath + @"\" + folderDirName;
  
          Directory.CreateDirectory(folderDirPath);
  
          string desPdfPath = folderDirPath + @"\" + "test.pdf";
  
          File.Copy(sourcePdfPath, desPdfPath, true);
  
      }
  </code></pre>
  
  <p>The method above creates a new folder and copies the pdf file to a new folder.
  It creates this dir tree:</p>
  
  <pre><code>TESTDATA
    -Data00000000
        -test.pdf
    -Data00000001
        -test.pdf
  ....
    -Data0000000N
        -test.pdf
  </code></pre>
  
  <p>I tried calling the <code>CreateFolderAndCopyFile</code> method in a <code>Parallel.ForEach</code> loop.</p>
  
  <pre><code>    private static void Func&lt;T&gt;(IEnumerable&lt;T&gt; docs)
      {
          int index = 0;
          Parallel.ForEach(docs, doc =&gt;
                                     {
                                         CreateFolderAndCopyFile(index);
                                         index++;
                                     });
      }
  </code></pre>
  
  <p>When I run this code it finishes with the following error:</p>
  
  <blockquote>
    <p>The process cannot access the file 'c:\testdata\Data00001102\test.pdf'
    because it is being used by another process.</p>
  </blockquote>
  
  <p>But first it created 1111 new folders and copied test.pdf about 1111 times before I got this error.</p>
  
  <p>What caused this behaviour and how can it be resolved?</p>
  
  <p><strong>EDITED:</strong> </p>
  
  <p>Code above was toy sample, sorry for hard coded strings
  <strong>Conclusion: Parallel method is slow.</strong></p>
  
  <p>Tomorrow I try some methods from <a href="https://stackoverflow.com/questions/955911/how-to-write-super-fast-file-streaming-code-in-c">How to write super-fast file-streaming code in C#?</a>. </p>
  
  <p>especially:  <a href="http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/" rel="nofollow noreferrer">http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/</a></p>