Running the C# compiler from a C# program

左心房为你撑大大i 提交于 2019-12-06 13:57:34

问题


I am trying to build a C# program that converts a different language into C# code. I have the program working fine, converting the code and writing it to a .cs file. I want to have this file automatically be compiled, and run, however I cannot figure out how to do this with C#.

I can do it manually by simply running a batch file I wrote, and I attempted to run this batch file from C# using the System.Diagnostics.Process class. When it ran it gave an error within the batch code itself, saying that none of the commands were found (the usual "not an executable, batch file etc"). I can't figure out why it runs normally, but not when ran from C#.

Here's the batch file code: C:\Program_Files_(x86)\Microsoft_Visual_Studio 10.0\VC\bin\amd64\vcvars64.bat csc %1.cs pause

and the function that calls it:

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "compiler\\compile.bat";
process.StartInfo.Arguments = " "+fileName;
process.Start();
process.WaitForExit();
process.StartInfo.FileName = fileName + ".exe";
process.Start();
process.WaitForExit();
Console.WriteLine("done");

Any help would be greatly appreciated.


回答1:


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);
        }
    }
}



回答2:


You can programmatically compile your code inside of C# using the CSharpCodeProvider class.



来源:https://stackoverflow.com/questions/7721406/running-the-c-sharp-compiler-from-a-c-sharp-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!