-->

Running the C# compiler from a C# program

2020-08-03 09:15发布

问题:

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.