从运行C#程序的C#编译器 [英] Running the C# compiler from a C# program

查看:177
本文介绍了从运行C#程序的C#编译器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图构建一个转换成不同的语言为C#code C#程序。我有计划做工精细,转换code和写入到一个cs文件。我想有这个文件被自动编译和运行,但我无法弄清楚如何使用C#做到这一点。

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#.

我可以简单地通过运行一个批处理文件,我写了做手工,我试图运行从C#使用的System.Diagnostics.Process类此批处理文件。当它运行它批code本身给了一个错误,他说,没有命令被发现(通常的不是一个可执行文件,批处理文件等)。我想不通为什么它运行正常,但不能从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#.

下面是该批处理文件code:
    C:\\ Program_Files_(x86)的\\ Microsoft_Visual_Studio 10.0 \\ VC \\ BIN \\ AMD64 \\ vcvars64.bat
    CSC%1.cs
    暂停

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

和调用它的功能:

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

任何帮助将大大AP preciated。

Any help would be greatly appreciated.

推荐答案

不要调用C#编译器或使用批处理脚本.NET plataform的任何编译器 - 这是一个糟糕的实践。为此,您可以仅使用C#。
使用 codeDomProvider 类,你可以随便写这一点。

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

这篇关于从运行C#程序的C#编译器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆