代码控制编译C#程序
前两天翻看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 CSharpComplierControl8: {9: class Program10: {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: else29: {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: else51: {52: compilerResults = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromFile(compilerParameters, sourceCode.FullName);53: }54: if (compilerResults.Errors.Count > 0)55:补充:软件开发 , C# ,
上一个:C#实现关机、重启、注销
下一个:C#实现大数相乘