title: Compiling many external .cs files into .dll using CodeProvider
body: <p>I'm trying to write a program that can take user-generated .cs files and compile them into a library for later use (really just to prevent re-compiling them the next time the program starts). When I try to compile them into a .dll, I get an error saying that the file is in use by another program.</p>
  
  <p>Here's my implementation:</p>
  
  <pre><code>CompilerParameters params = new CompilerParameters();
  params.GenerateExecutable = false;
  params.GenerateInMemory = false;
  params.OutputAssembly = "test.dll";
  params.TreatWarningsAsErrors = true;
  
  CSharpCodeProvider provider = new CSharpCodeProvider();
  
  DirectoryInfo di = DirectoryInfo di = new DirectoryInfo(path);
  FileInfo[] files = di.GetFiles("*.cs", SearchOption.AllDirectories);
  foreach(FileInfo fi in files)
  {
      CompilerResults cr = provider.CompileAssemblyFromFile(params, fi.FullName);
      if(cr.Errors.Count &gt; 0)
      {
          foreach(CompilerError ce in cr.Errors)
          {
              Console.WriteLine(ce.ToString());
          }
      }
  }
  </code></pre>
  
  <p>The first file compiles just fine. Every file after that, though, gives me this error:</p>
  
  <pre><code>CS0016: Cannot write to output file "temp.dll" -- The process cannot access the file because it is being used by another process.
  </code></pre>
  
  <p>Why is it giving me this error? Do I need to invoke the compiler a different way if I intend to add many classes to an assembly?</p>
  
  <p>Thanks for your help.</p>