Created
June 17, 2017 15:26
-
-
Save Cazzar/900e1bba000cf82ca004ff1f3222ad8b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.CSharp; | |
using System.CodeDom.Compiler; | |
using System.Reflection; | |
using System; | |
using System.Text; | |
public class A | |
{ | |
public static void Main(string[] args) | |
{ | |
CSharpCodeProvider provider = new CSharpCodeProvider(); | |
CompilerParameters parameters = new CompilerParameters(); | |
string code = @" | |
using System; | |
namespace First | |
{ | |
public class Program | |
{ | |
public static void Main() | |
{ | |
" + | |
"Console.WriteLine(\"Hello, world!\");" | |
+ @" | |
} | |
} | |
} | |
"; | |
// Reference to System.Drawing library | |
//parameters.ReferencedAssemblies.Add("System.Drawing.dll"); | |
// True - memory generation, false - external file generation | |
parameters.GenerateInMemory = true; | |
// True - exe file generation, false - dll file generation | |
parameters.GenerateExecutable = true; | |
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); | |
if (results.Errors.HasErrors) | |
{ | |
StringBuilder sb = new StringBuilder(); | |
foreach (CompilerError error in results.Errors) | |
{ | |
sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText)); | |
} | |
throw new InvalidOperationException(sb.ToString()); | |
} | |
Assembly assembly = results.CompiledAssembly; | |
Type program = assembly.GetType("First.Program"); | |
MethodInfo main = program.GetMethod("Main"); | |
main.Invoke(null, null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment