Advertisement
BaSs_HaXoR

Awesome (atruntime) string-compiled code :)

Sep 11th, 2014
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. //SOURCE: http://stackoverflow.com/questions/4181668/execute-c-sharp-code-at-runtime-from-code-file
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Reflection;
  9. using System.Net;
  10. using Microsoft.CSharp;
  11. using System.CodeDom.Compiler;
  12.  
  13. namespace ConsoleApplication2
  14. {
  15.     class Program
  16.     {
  17.         static void Main(string[] args)
  18.         {
  19.             string source =
  20.             @"
  21. namespace Foo
  22. {
  23.    public class Bar
  24.    {
  25.        public void SayHello()
  26.        {
  27.            System.Console.WriteLine(""Hello World"");
  28.        }
  29.    }
  30. }
  31.            ";
  32.  
  33.              Dictionary<string, string> providerOptions = new Dictionary<string, string>
  34.                 {
  35.                     {"CompilerVersion", "v3.5"}
  36.                 };
  37.             CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
  38.  
  39.             CompilerParameters compilerParams = new CompilerParameters
  40.                 {GenerateInMemory = true,
  41.                  GenerateExecutable = false};
  42.  
  43.             CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
  44.  
  45.             if (results.Errors.Count != 0)
  46.                 throw new Exception("Mission failed!");
  47.  
  48.             object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
  49.             MethodInfo mi = o.GetType().GetMethod("SayHello");
  50.             mi.Invoke(o, null);
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement