【学习】从.txt文件读取生成编译代码。

 1  string code = null;
 2                 String projectName = Assembly.GetExecutingAssembly().GetName().Name;
 3                 // 1. 生成要编译的代码。(示例为了简单直接从程序集内的资源中读取)
 4                 Stream stram = Assembly.GetExecutingAssembly()
 5                             .GetManifestResourceStream(projectName + ".code.txt");
 6                 using (StreamReader sr = new StreamReader(stram, Encoding.GetEncoding("GB2312")))
 7                 {
 8                     code = sr.ReadToEnd();
 9                 }
10 
11                 //Console.WriteLine(code);
12 
13                 // 2. 设置编译参数,主要是指定将要引用哪些程序集
14                 CompilerParameters cp = new CompilerParameters();
15                 cp.GenerateExecutable = false;
16                 cp.GenerateInMemory = true;
17                 cp.ReferencedAssemblies.Add("System.dll");
18 
19                 // 3. 获取编译器并编译代码
20                 // 由于我的代码使用了【自动属性】特性,所以需要 C# .3.5版本的编译器。
21                 // 获取与CLR匹配版本的C#编译器可以这样写:CodeDomProvider.CreateProvider("CSharp")
22 
23                 Dictionary<string, string> dict = new Dictionary<string, string>();
24                 dict["CompilerVersion"] = "v4.0";
25                 dict["WarnAsError"] = "true";
26 
27                 CompilerResults cr = new CSharpCodeProvider(dict).CompileAssemblyFromSource(cp, code);
28 
29                 // 4. 检查有没有编译错误
30                 if (cr.Errors != null && cr.Errors.HasErrors)
31                 {
32                     foreach (CompilerError error in cr.Errors)
33                         Console.WriteLine(error.ErrorText);
34 
35                     return;
36                 }
37 
38                 // 5. 获取编译结果,它是编译后的程序集
39                 Assembly asm = cr.CompiledAssembly;
40 
41                 // 6. 找到目标方法,并调用
42                 Type t = asm.GetType("demo.test");
43                 MethodInfo method = t.GetMethod("Main");
44                 method.Invoke(null, null);
控制台源码
 1 using System;
 2 namespace demo
 3 {
 4     public class demoClass
 5     {
 6         public int Id { get; set; }
 7 
 8         public string Name;
 9 
10         public int Add(int a, int b)
11         {
12             return a + b;
13         }
14     }
15 
16     public class test
17     {
18         public static void Main()
19         {
20             Console.WriteLine("ok");
21         }
22     }
23 }
code.txt

注意:需要将code.txt设置为嵌入的资源

好好学习,天天向上。
原文地址:https://www.cnblogs.com/Zhengxue/p/8920343.html