Running the C# compiler from a C# program

拜拜、爱过 提交于 2019-12-04 19:37:26

Don't call the C# compiler or any compiler of .net plataform using a batch script - it's a bad pratice. You can do this using only C#. using the CodeDomProvider class you can write this easily.

  static void CompileCSharp(string code) {
    CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
    ICodeCompiler compiler = provider.CreateCompiler();
    CompilerParameters parameters = new CompilerParameters();
    parameters.OutputAssembly = @"D:\foo.exe";
    parameters.GenerateExecutable = true;
    CompilerResults results = compiler.CompileAssemblyFromSource(parameters, code);
    if (results.Output.Count == 0)
    {
        Console.WriteLine("success!");
    }
    else
    {
        CompilerErrorCollection CErros = results.Errors;
        foreach (CompilerError err in CErros)
        {
            string msg = string.Format("Erro:{0} on line{1} file name:{2}", err.Line, err.ErrorText, err.FileName);
            Console.WriteLine(msg);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!