CSharp-CodeDom生成和编译源代码

CSharp-CodeDom生成和编译源代码

System.CodeDom.Compiler 命名空间提供了从 CodeDOM 对象图生成源代码和用受支持的编译器管理编译的接口。 代码提供程序可根据 CodeDOM 图,用某种编程语言生成源代码。 从 CodeDomProvider 派生的类通常可以提供一些方法,用于生成和编译提供程序支持的语言代码。

参考:

在 CodeDOM 图中生成和编译源代码

CodeDomProvider Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using Microsoft.JScript;

// This example demonstrates building a Hello World program graph
// using System.CodeDom elements. It calls code generator and
// code compiler methods to build the program using CSharp, VB, or
// JScript. A Windows Forms interface is included. Note: Code
// must be compiled and linked with the Microsoft.JScript assembly.
namespace WindowsFormsApp1
{
class CodeDomExample
{
// Build a Hello World program graph using
// System.CodeDom types.
public static CodeCompileUnit BuildHelloWorldGraph()
{
// Create a new CodeCompileUnit to contain
// the program graph.
CodeCompileUnit compileUnit = new CodeCompileUnit();

// Declare a new namespace called Samples.
CodeNamespace samples = new CodeNamespace("Samples");
// Add the new namespace to the compile unit.
compileUnit.Namespaces.Add(samples);

// Add the new namespace import for the System namespace.
samples.Imports.Add(new CodeNamespaceImport("System"));

// Declare a new type called Class1.
CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");
// Add the new type to the namespace type collection.
samples.Types.Add(class1);

// Declare a new code entry point method.
CodeEntryPointMethod start = new CodeEntryPointMethod();

// Create a type reference for the System.Console class.
CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console");

// Build a Console.WriteLine statement.
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(
csSystemConsoleType, "WriteLine",
new CodePrimitiveExpression("Hello World!"));

// Add the WriteLine call to the statement collection.
start.Statements.Add(cs1);

// Build another Console.WriteLine statement.
CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression(
csSystemConsoleType, "WriteLine",
new CodePrimitiveExpression("Press the Enter key to continue."));

// Add the WriteLine call to the statement collection.
start.Statements.Add(cs2);

// Build a call to System.Console.ReadLine.
CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression(
csSystemConsoleType, "ReadLine");

// Add the ReadLine statement.
start.Statements.Add(csReadLine);

// Add the code entry point method to
// the Members collection of the type.
class1.Members.Add(start);

return compileUnit;
}

public static void GenerateCode(CodeDomProvider provider,
CodeCompileUnit compileunit)
{
// Build the source file name with the appropriate
// language extension.
String sourceFile;
if (provider.FileExtension[0] == '.')
{
sourceFile = "TestGraph" + provider.FileExtension;
}
else
{
sourceFile = "TestGraph." + provider.FileExtension;
}

// Create an IndentedTextWriter, constructed with
// a StreamWriter to the source file.
IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(sourceFile, false), " ");
// Generate source code using the code generator.
provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions());
// Close the output file.
tw.Close();
}

public static CompilerResults CompileCode(CodeDomProvider provider,
String sourceFile,
String exeFile)
{
// Configure a CompilerParameters that links System.dll
// and produces the specified executable file.
String[] referenceAssemblies = { "System.dll" };
CompilerParameters cp = new CompilerParameters(referenceAssemblies,
exeFile, false);
// Generate an executable rather than a DLL file.
cp.GenerateExecutable = true;

// Invoke compilation.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile);
// Return the results of compilation.
return cr;
}
}

public class CodeDomExampleForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Button run_button = new System.Windows.Forms.Button();
private System.Windows.Forms.Button compile_button = new System.Windows.Forms.Button();
private System.Windows.Forms.Button generate_button = new System.Windows.Forms.Button();
private System.Windows.Forms.TextBox textBox1 = new System.Windows.Forms.TextBox();
private System.Windows.Forms.ComboBox comboBox1 = new System.Windows.Forms.ComboBox();
private System.Windows.Forms.Label label1 = new System.Windows.Forms.Label();

private void generate_button_Click(object sender, System.EventArgs e)
{
CodeDomProvider provider = GetCurrentProvider();
CodeDomExample.GenerateCode(provider, CodeDomExample.BuildHelloWorldGraph());

// Build the source file name with the appropriate
// language extension.
String sourceFile;
if (provider.FileExtension[0] == '.')
{
sourceFile = "TestGraph" + provider.FileExtension;
}
else
{
sourceFile = "TestGraph." + provider.FileExtension;
}

// Read in the generated source file and
// display the source text.
StreamReader sr = new StreamReader(sourceFile);
textBox1.Text = sr.ReadToEnd();
sr.Close();
}

private void compile_button_Click(object sender, System.EventArgs e)
{
CodeDomProvider provider = GetCurrentProvider();

// Build the source file name with the appropriate
// language extension.
String sourceFile;
if (provider.FileExtension[0] == '.')
{
sourceFile = "TestGraph" + provider.FileExtension;
}
else
{
sourceFile = "TestGraph." + provider.FileExtension;
}

// Compile the source file into an executable output file.
CompilerResults cr = CodeDomExample.CompileCode(provider,
sourceFile,
"TestGraph.exe");

if (cr.Errors.Count > 0)
{
// Display compilation errors.
textBox1.Text = "Errors encountered while building " +
sourceFile + " into " + cr.PathToAssembly + ": \r\n\n";
foreach (CompilerError ce in cr.Errors)
textBox1.AppendText(ce.ToString() + "\r\n");
run_button.Enabled = false;
}
else
{
textBox1.Text = "Source " + sourceFile + " built into " +
cr.PathToAssembly + " with no errors.";
run_button.Enabled = true;
}
}

private void run_button_Click(object sender,
System.EventArgs e)
{
Process.Start("TestGraph.exe");
}

private CodeDomProvider GetCurrentProvider()
{
CodeDomProvider provider;
switch ((string)this.comboBox1.SelectedItem)
{
case "CSharp":
provider = CodeDomProvider.CreateProvider("CSharp");
break;
case "Visual Basic":
provider = CodeDomProvider.CreateProvider("VisualBasic");
break;
case "JScript":
provider = CodeDomProvider.CreateProvider("JScript");
break;
default:
provider = CodeDomProvider.CreateProvider("CSharp");
break;
}
return provider;
}

public CodeDomExampleForm()
{
this.SuspendLayout();
// Set properties for label1
this.label1.Location = new System.Drawing.Point(395, 20);
this.label1.Size = new Size(180, 22);
this.label1.Text = "Select a programming language:";
// Set properties for comboBox1
this.comboBox1.Location = new System.Drawing.Point(560, 16);
this.comboBox1.Size = new Size(190, 23);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Items.AddRange(new string[] { "CSharp", "Visual Basic", "JScript" });
this.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Left
| System.Windows.Forms.AnchorStyles.Right
| System.Windows.Forms.AnchorStyles.Top;
this.comboBox1.SelectedIndex = 0;
// Set properties for generate_button.
this.generate_button.Location = new System.Drawing.Point(8, 16);
this.generate_button.Name = "generate_button";
this.generate_button.Size = new System.Drawing.Size(120, 23);
this.generate_button.Text = "Generate Code";
this.generate_button.Click += new System.EventHandler(this.generate_button_Click);
// Set properties for compile_button.
this.compile_button.Location = new System.Drawing.Point(136, 16);
this.compile_button.Name = "compile_button";
this.compile_button.Size = new System.Drawing.Size(120, 23);
this.compile_button.Text = "Compile";
this.compile_button.Click += new System.EventHandler(this.compile_button_Click);
// Set properties for run_button.
this.run_button.Enabled = false;
this.run_button.Location = new System.Drawing.Point(264, 16);
this.run_button.Name = "run_button";
this.run_button.Size = new System.Drawing.Size(120, 23);
this.run_button.Text = "Run";
this.run_button.Click += new System.EventHandler(this.run_button_Click);
// Set properties for textBox1.
this.textBox1.Anchor = (System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Bottom
| System.Windows.Forms.AnchorStyles.Left
| System.Windows.Forms.AnchorStyles.Right);
this.textBox1.Location = new System.Drawing.Point(8, 48);
this.textBox1.Multiline = true;
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(744, 280);
this.textBox1.Text = "";
// Set properties for the CodeDomExampleForm.
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(768, 340);
this.MinimumSize = new System.Drawing.Size(750, 340);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.textBox1,
this.run_button, this.compile_button, this.generate_button,
this.comboBox1, this.label1 });
this.Name = "CodeDomExampleForm";
this.Text = "CodeDom Hello World Example";
this.ResumeLayout(false);
}

protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}

[STAThread]
static void Main()
{
Application.Run(new CodeDomExampleForm());
}
}
}