• 代码控制编译C#程序
  •  2012/3/23 16:30:55 | 分类:C# | 阅读:635
  • 导读:前两天翻看玩,发现一个挺有趣的功能,可以直接使用代码控制csharp/target=_blank#程序的编译。有这么个东西,要是有些程序需要实现即时修改代码再编译成程序集的功能就比较方便了。话说,et该不…


  • 前两天翻看MSDN玩,发现一个挺有趣的功能,可以直接使用代码控制csharp/" target="_blank">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);
    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:       				
                                    
    (学 习 吧:www.xuexibar.cn)

    此文章为学 习 整理或来自网络,内容仅供访问者参考,版权归原作者所有,转载请注明出处!