using System;<br> using System.CodeDom.Compiler;<br> using System.Collections. Generic ;<br> using Microsoft.CSharp;<br><br> namespace ConsoleCompiler<br>{<br> internal class Program<br> {<br> private static void Main( string [] args)<br> {<br> // Source code <br> string source =<br> @"<br>namespace Foo<br>{<br> public class Bar<br> {<br> static void Main(string[] args)<br> {<br> Bar.SayHello();<br> }<br><br> public static void SayHello()<br> {<br> System.Console.WriteLine(" "Hello World" ");<br> }<br> }<br>}<br> " ;<br><br> // <br> Dictionary< string , string > providerOptions = new Dictionary< string , string ><br> {<br> { "CompilerVersion" , "v3.5" }<br> };<br> CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);<br><br> CompilerParameters compilerParams = new CompilerParameters<br> {OutputAssembly = "D:\\Foo.EXE" , GenerateExecutable = true };<br><br> // <br> CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);<br><br> // <br> Console .WriteLine( "Number of Errors: {0}" , results.Errors.Count);<br> foreach (CompilerError err in results.Errors)<br> {<br> Console .WriteLine( "ERROR {0}" , err.ErrorText);<br> }<br> }<br> }<br>} <br><br> * This source code was highlighted with Source Code Highlighter .
string source = @"<br> using System.Collections.Generic;<br>using System.Linq; <br><br>namespace Foo<br>{<br> public class Bar<br> {<br> static void Main(string[] args)<br> {<br> Bar.SayHello();<br> }<br><br> public static void SayHello()<br> {<br> System.Console.WriteLine(" "Hello World" ");<br> System.Console.WriteLine( string.Join(" "," ", Enumerable.Range(0,10).Select(n=>n.ToString()).ToArray() ) ); <br> }<br> }<br>}" ; <br><br> * This source code was highlighted with Source Code Highlighter .
compilerParams.ReferencedAssemblies.Add( "System.Core.Dll" ); <br><br> * This source code was highlighted with Source Code Highlighter .
stringsource = @"<br>using System.Collections.Generic;<br>using System.Linq;<br><br>namespace Foo<br>{<br> public class Bar<br> {<br> public static void SayHello()<br> {<br> System.Console.WriteLine(" "Hello World" ");<br> System.Console.WriteLine( string.Join(" "," ", Enumerable.Range(0,10).Select(n=>n.ToString()).ToArray() ) );<br> }<br> }<br>}" ; <br><br> * This source code was highlighted with Source Code Highlighter .
const string outputAssembly = "D:\\Foo.dll" ;<br>CompilerParameters compilerParams = new CompilerParameters {OutputAssembly = outputAssembly, GenerateExecutable = false }; <br><br> * This source code was highlighted with Source Code Highlighter .
Console .WriteLine( "Try Assembly:" );<br> Assembly assembly = Assembly .LoadFile(outputAssembly);<br>Type type = assembly.GetType( "Foo.Bar" );<br>MethodInfo method = type.GetMethod( "SayHello" );<br>method.Invoke( null , null ); <br><br> * This source code was highlighted with Source Code Highlighter .
Source: https://habr.com/ru/post/67431/
All Articles