title: C# AppDomain: Execute assembly from entry point
body: <p>I am trying to create a Windows sandbox application, building upon the "How to" found here: "<a href="https://msdn.microsoft.com/en-us/library/bb763046(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/bb763046(v=vs.110).aspx</a>"</p>
  
  <p>In the example it loads a specific type from a DLL whereas I would like to be able to execute an assembly from its entry point with restricted permissions.</p>
  
  <p>The program I am using for testing purposes is a simple hello world application.</p>
  
  <pre><code>using System;
  
  namespace ConsoleApplication1
  {
      class Program
      {
          static void Main(string[] args)
          {
              Console.WriteLine("Hello World!");
              Console.Read();
          }
      }
  }
  </code></pre>
  
  <p>I have tried two different methods to try and achieve this.</p>
  
  <p>Method 1.</p>
  
  <p>Use the "MethodInfo.Invoke" method on the entry point of the assembly.</p>
  
  <pre><code>MethodInfo target = Assembly.Load(assemblyName).EntryPoint;
  target.Invoke(null, parameters);
  </code></pre>
  
  <p>This produces a Method Access Exception due to the main method being non-public. A simple way around this would be to make the main method public but I will not have this sort of access to the assemblies that are intended to be used with this application.</p>
  
  <p>Method 2.</p>
  
  <p>Use the "AppDomain.ExecuteAssembly" method as shown below.</p>
  
  <pre><code>newDomain.ExecuteAssembly(filePath, parameters);
  </code></pre>
  
  <p>This requires that the app domain has both File IO Permission and UI Permission for the assembly to be executed but I want to be able to restrict the assembly from having these permissions.</p>
  
  <p>Is there a way to execute an assembly from it's entry point within a permission restricted app domain?</p>
  
  <p>EDIT: The assembly's location is provided from an Open File Dialog and is then passed to the following method.</p>
  
  <pre><code>public int RunAssembly(string filePath, string[] parameters)
  {
      AppDomainSetup adSetup = new AppDomainSetup();
      adSetup.ApplicationBase = Path.GetDirectoryName(filePath);
  
      PermissionSet permSet = new PermissionSet(PermissionState.None);
      permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
  
      StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence&lt;StrongName&gt;();
  
      newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);
  
      return newDomain.ExecuteAssembly(filePath, parameters);
  }
  </code></pre>
  
  <p>As you can see the only permission I would like to give the new app domain is the ability to run. Whereas it required File IO and UI permissions for the ExecuteAssembly method to work correctly.</p>