在運行時編寫代碼並編譯執行。如下所示。
Open按鈕打開任意文本文件,並載入到TextBox。載入後可更改。
Compile按鈕進行編譯和執行。具體代碼如下。
代碼
1 using System;
2 using System.Windows.Forms;
3 using System.IO;
4 using System.CodeDom.Compiler;
5 using Microsoft.CSharp;
6 using System.Reflection;
7
8 namespace DynamicCodeCompiler
9 {
10 public partial class Form1 : Form
11 {
12 string dynammicCode;
13
14 public Form1()
15 {
16 InitializeComponent();
17 }
18
19 //打開文件並載入代碼
20 private void button1_Click(object sender, EventArgs e)
21 {
22 OpenFileDialog ofd = new OpenFileDialog();
23 ofd.Multiselect = false;
24
25 if (ofd.ShowDialog()==DialogResult.OK)
26 {
27 FileStream fs = new FileStream(ofd.FileName,FileMode.Open);
28 StreamReader sr = new StreamReader(fs);
29 dynammicCode = sr.ReadToEnd();
30 textBox1.Text = dynammicCode;
31 }
32 }
33
34 private void button2_Click(object sender, EventArgs e)
35 {
36 if (textBox1.Text != null)
37 {
38 // 1.CSharpCodePrivoder
39 CSharpCodeProvider objCSharpCodePrivoder = new