============================================== Dynamic Compiling program ideas
* 0, put C # in string object in the form of strings
* 1, instantiate a C # compiler: CSharpCodeProvider
* 2, create the compiler environment (and configure the environment): CompilerParameters
* 3, start compiling: Ccp.compileassemblyfromsource (CP, ABC);
* 4, return build result: CompilerResults
* "5, you can invoke the assembly using reflection"
============================================== What is a program domain?
Before. NET technology, a process is an application-independent boundary,
In the. NET architecture, an application has a new boundary, which is the program domain. objects can be reasonably allocated in different program domains,
You can uninstall a program domain
650) this.width=650; "title=" Sogou 20141204001416.png "alt=" wkiol1r_odegdlmhaadz56ngj0y634.jpg "src="/http S3.51cto.com/wyfs02/m01/54/54/wkiol1r_odegdlmhaadz56ngj0y634.jpg "/>
The role of the ============================================== program domain
If the assembly is dynamically loaded, and you need to unload the assembly after use, the application domain is very
Use. In the main application domain, you cannot delete an assembly that has already been loaded, but you can terminate the application domain in which the
All assemblies that are loaded in the program domain are purged from memory.
============================================== Example:
650) this.width=650; "style=" Float:none; "title=" Sogou 20141204000852.png "alt=" wkiol1r_niwhhptnaacbdlctbss429.jpg "src = "Http://s3.51cto.com/wyfs02/M01/54/54/wKioL1R_NiWhHPtNAACbdLcTBss429.jpg"/>
650) this.width=650; "style=" Float:none; "title=" Sogou 20141204000901.png "alt=" wkiom1r_nznjkix3aacammhqhqa341.jpg "src = "Http://s3.51cto.com/wyfs02/M01/54/55/wKiom1R_NZnjKIx3AACAmMHQhQA341.jpg"/>
--------------------------------------CompileType.cs (enum file)
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; namespace appdomaindemo{public enum Compiletype {console,//console output file//output file}}
--------------------------------------CompileCode.cs (Dynamically compiled program code class)
Using system;using system.collections.generic;using system.linq;using system.text;using system.threading.tasks;using system.io;using system.reflection;using microsoft.csharp;// Provides access to an instance of the C# code generator and code compiler. using system.codedom.compiler;//use is to manage the generation and compilation of source code for supported programming languages namespace appdomaindemo{ //marshalbyrefobject: Cross-domain access must inherit this class public class CompileCode : Marshalbyrefobject { public string compilecodego (String input, compiletype ct, out bool iserror) { Stringbuilder sb1 = new stringbuilder (); sb1. Append ("using system;"); &nbSp; sb1. Append ("using system.windows.forms;"); sb1. Append ("Public class program{public static void main (String[] args) {"); StringBuilder sb2 = new StringBuilder (); sb2. Append ("}"); sb2. Append ("Public void aa () {"); string bottom = "}}"; // Compiler csharpcodeprovider ccp = new csharpcodeprovider (); // Compile parameter Configuration compilerparameters cp = New compilerparameters (); //compilation result CompilerResults cr; //Console Output if (Ct == compiletype.console) { //setting whether to generate output in memory &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;CP. generateinmemory = true; } else//compiled as an executable file { Whether the //is an executable file &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;CP. generateexecutable = true; //configuration output file path &NBSP;&NBSP;&NBSP;&NBSP;CP. Outputassembly = directory.getcurrentdirectory () + "/" + datetime.now.tostring (" Yyyymmhhddmmss ") + ". exe "; } //Referencing Assemblies &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;CP. Referencedassemblies.add ("System.Windows.Forms.dll"); //compilation cr = ccp.compileassemblyfromsource (CP,&NBSP;SB1. ToString () + input + sb2. ToString () + input + bottom); if (CR. errors.haserrors)//Edit results appear abnormal { IsError = True; string error = ""; for (INT&NBSP;I&NBSP;=&NBSP;0;&NBSP;I&NBSP;<&NBSP;CR. errors.count; i++) { error += string. Format ("affects the number of rows: {0}, error message: {1}\r\n", &NBSP;CR. Errors[i]. Line.tostring (), &NBSP;CR. Errors[i]. ErrorText); } return error; } else { iserror = false; The //is used to accept console output information &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp; stringwriter sw = new stringwriter (); console.setout (SW); //gets the compiled assembly [reflection] &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;ASSEMBLY&NBSP;ASB&NBSP;=&NBSP;CR. compiledassembly; //Get class TYPE&NBSP;T&NBSP;=&NBSP;ASB. GetType ("program"); //non-static methods require instantiation classes object o = activator.createinstance (t); How to get // methodinfo m = t.getmethod ("AA"); //Execution Methods m.invoke (o, null); //returns the results of the console output &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;SW. ToString (); } } }}
--------------------------------------AppDomainCode.cs (Create uninstaller Domain Class)
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks;namespace AppDomainDemo{ public class appdomaincode { public string Appdomaincodego (String input, compiletype ct, out bool iserror) { / /Create a program field AppDomain app = Appdomain.createdomain ("Zhangdi"); // Create an instance of the compilecode cc = type (Compilecode) app. Createinstanceandunwrap ("Appdomaindemo", "Appdomaindemo.compilecode"); string &NBSP;RESULT=&NBSP;CC. Compilecodego (Input, ct, out iserror); //Uninstall a program domain AppDomain.Unload (APP); return result; } }}
--------------------------------------Form1.cs (Form daemon)
using system;using system.collections.generic;using system.componentmodel;using system.data;using system.drawing;using system.linq;using system.text;using system.threading.tasks;using system.windows.forms;namespace appdomaindemo{ /* ************************************* * The code cannot be Console.readkey (); * Click tap My Output console button "An error occurred: The target of the call has an exception" * This mistake I've been looking for a few days, hang dad ************************************* */ public partial class form1 : form { public form1 () { InitializeComponent (); } string str = "Console.WriteLine (\" Aasdasd\ "); Console.ReadLine (); "; /// <summary> /// point I output the console /// </summary> /// <param name= "Sender" ></param> /// <param name= "E" ></param> private void btnconsole_click (Object sender, eventargs e) { appdomaincode adc = new appdomaincode (); bool iserror; string result = adc. Appdomaincodego (Str, compiletype.console, out iserror); richTextBox1.Text = result; } /// <summary> /// point I output executable file /// </ Summary> /// <param name= "Sender" ></param > /// <param name= "E" ></param> private void btnfile_click (object sender, Eventargs e) { appdomaincode adc = new appdomaincode (); bool iserror; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;STRING&NBSP;RESULT&NBSP;=&NBSP;ADC. Appdomaincodego (Str, compiletype.file, out iserror); richTextBox1.Text = result; } }}
This article is from the "program Ape's Home--hunter" blog, please be sure to keep this source http://962410314.blog.51cto.com/7563109/1586141
Dynamically compiling programs and creating uninstaller domains