In the case of learning .cs file, use the example of the .cs file, using the example, code actually compiles, the main code is as follows, the main code is as follows:
Namespace: use system.codedom; using system.codedom.compiler; using microsoft.csharp; using system.io;
private void button1_Click (object sender, System.EventArgs e) {CodeCompileUnit CompileUnit = new CodeCompileUnit (); CodeNamespace Samples = new CodeNamespace ( "Samples"); Samples.Imports.Add (new CodeNamespaceImport ( "System")); CompileUnit.Namespaces .Add (Samples); CODETYPEDECLATION CLASS1 = New CodeTypedeclaration ("Class1"); Samples.Types.Add (Class1);
CodeEntryPointMethod Start = new CodeEntryPointMethod (); // output HelloWord CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression (new CodeTypeReferenceExpression ( "System.Console"), "WriteLine", new CodePrimitiveExpression ( "Hello World!")); Start.Statements.Add (cs1 );
Class1.members.add (start); // csharpcodeProvider Province = new csharpcodeProvider (); // icodegenerator gen = provider.creategenerator (); generategraph (CompileUn);
} Public void GenerateGraph (CodeCompileUnit compileunit) {// Obtains an ICodeGenerator from a CodeDomProvider class CSharpCodeProvider provider = new CSharpCodeProvider ();. ICodeGenerator gen = provider.CreateGenerator ();. // Creates a StreamWriter to an output file StreamWriter sw = new StreamWriter ("D: //Testgraph.cs", False);
// generates Source Code Using The Code Generator. Gen.GeneratecodeFromCompileunit (CompileUnit, SW, New ??? codegeneratorOptions ()); // closs the output files. Sw.close ();}
private void button2_Click (object sender, System.EventArgs e) {CompileCode ( "d: //TestGraph.cs");} // edit the generated Exepublic CompilerResults CompileCode (string filepath) {// Obtains an ICodeCompiler from a CodeDomProvider class CSharpCodeProvider. provider = new CSharpCodeProvider (); ICodeCompiler compiler = provider.CreateCompiler ();. // Configures a compiler parameters object which links System.dll and // generates a file name based on the specified source file name CompilerParameters cp = new CompilerParameters (new String [] {"system.dll"}, filepath.substring (0, filepath.lastindexof (".") 1) "EXE", FALSE);
// indeicates tria an executable rather Than a .dll Should be generated. Cp.generateexecutable = true;
// Invokes compilation. CompilerResults cr = compiler.compileAssemblyfromfile (CP, FilePath);
// Returns the results of compiration. Return Cr;}
Examples in the help in: .NET Framework-> Using .NET Framework program -> Dynamic generation and compile Source code indicated in multiple languages