前兩天翻看MSDN玩,發現一個挺有趣的功能,可以直接使用代碼控制C#程序的編譯。有這麼個東西,要是有些程序需要實現即時修改代碼再編譯成程序集的功能就比較方便了。...話說,ASP.Net該不會是用這個實現的吧?
先上一段代碼,功能是編譯參數中引用的文件中包含的代碼,如果不帶參數則編譯一段自帶的代碼:
1: using System;
2: using System.CodeDom;
3: using System.CodeDom.Compiler;
4: using Microsoft.CSharp;
5: using System.IO;
6:
7: namespace CSharpComplierControl
8: {
9: class Program
10: {
11: static void Main(string[] args)
12: {
13: string code = @"
14: using System;
15: namespace Application{
16: class App{
17: public static void Main(string[] args){
18: Console.WriteLine(" + ""Hello,haha"" + @");
19: }
20: }
21: }";
22: bool noInput = false;
23: FileInfo sourceCode = null;
24: if (args.Length == 0)
25: {
26: noInput = true;
27: }
28: else
29: {
30: sourceCode = new FileInfo(args[0]);
31: if (!sourceCode.Exists)
32: {
33: noInput = true;
34: }
35: }
36:
37: string objectExecutive = "test.exe";
38: CompilerParameters compilerParameters = new CompilerParameters();
39: compilerParameters.GenerateExecutable = true;
40: compilerParameters.OutputAssembly = objectExecutive;
41: compilerParameters.IncludeDebugInformation = true;
42: compilerParameters.GenerateInMemory = false;
43: compilerParameters.TreatWarningsAsErrors = false;
44:
45: CompilerResults compilerResults = null;
46: if (noInput)
47: {
48: compilerResults = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(compilerParameters, code);
49: }
50: else
51: {
52: compilerResults = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromFile(compilerParameters, sourceCode.FullName);
53: }
54: if (compilerResults.Errors.Count > 0)
55: