title: In .NET 4.0, how do I 'sandbox' an in-memory assembly and execute a method?
body: <p>Here is the reason why this question was being asked: <a href="http://www.devplusplus.com/Tests/CSharp/Hello_World">www.devplusplus.com/Tests/CSharp/Hello_World</a>.</p>
  
  <p>While similar questions were asked before, the many answers online have several issues:</p>
  
  <ol>
  <li>This must be done ".Net 4.0" style, not legacy mode.</li>
  <li>The assembly is in-memory and will only be in memory, it <strong>cannot</strong> be written to the file system.</li>
  <li>I would like to limit all access to the file-system, network, etc. </li>
  </ol>
  
  <p>Something like this:</p>
  
  <pre><code>    var evidence = new Evidence();
      evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
      var permissionSet = SecurityManager.GetStandardSandbox(evidence);
  </code></pre>
  
  <p>So far, I cannot find a way to create an AppDomain and load an assembly <strong>THAT IS NOT ON THE FILE SYSTEM</strong>, but rather in RAM.</p>
  
  <p>Again, the reasons why the other solutions didn't work are identified above: 1. Many were for pre-4.0, and 2. Many relied on the ".Load" method pointing to the file system.</p>
  
  <p>Answer 2: I have an assembly reference due to it being generated by the <code>CSharpCodeProvider</code> class, so if you know a way to turn <em>that</em> into a byte array, that would be perfect!</p>
  
  <h2>Sample Code to Show The Security Flaw</h2>
  
  <pre><code>var provider = new CSharpCodeProvider(new Dictionary&lt;String, String&gt;
      { { "CompilerVersion", "v4.0" } });
  
  var compilerparams = new CompilerParameters
      { GenerateExecutable = false, GenerateInMemory = true, };
  
  var compilerResults = provider.CompileAssemblyFromSource(compilerparams,
      string_Of_Code_From_A_User);
  
  var instanceOfSomeClass = compilerResults.CompiledAssembly
      .CreateInstance(className);
  
  // The 'DoSomething' method can write to the file system and I don't like that!
  instanceOfSomeClass.GetType().GetMethod("DoSomething")
      .Invoke(instanceOfSomeClass, null);
  </code></pre>
  
  <h2>So why can't I just save the assembly to a file first?</h2>
  
  <p>For two reasons:</p>
  
  <ol>
  <li>This code is on a shared web server with limited permissions to the file-system itself.</li>
  <li>This code may need to be run potentially thousands of times, and I don't want 1,000 dlls, even temporarily.</li>
  </ol>