Follow me on Twitter RSS FEED

C# Programmatically Compiling .cs files to executables

I was thinking of making a program that generates an executable which installs an application, but how to generate the executable?

public static void Compile(String Output, String code)
{
    CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
    CompilerParameters parameters = new CompilerParameters();
    //Make sure we generate an EXE, not a DLL
    parameters.GenerateExecutable = true;
    parameters.OutputAssembly = Output;
    CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code);
    if (results.Errors.Count > 0)
    {
        foreach (CompilerError CompErr in results.Errors)
        {
            Debug.WriteLine(
                "Line number " + CompErr.Line +
                ", Error Number: " + CompErr.ErrorNumber +
                ", '" + CompErr.ErrorText + ";" +
                Environment.NewLine + Environment.NewLine);
        }
    }
    else
    {
        Debug.WriteLine("Success!");
    }
}

In order to use this function, you must using these two classes:

using System.CodeDom.Compiler;
using System.Diagnostics;

Once you have that done, you're good to go! As a quick example, you can create a textarea named txt_code, a textbox named txt_output, and a button btn_submit. When btn_submit is clicked, then it will say:

Compile(txt_output.Text, txt_code.Text);

Which if you put a valid path in txt_output, and valid C# code in txt_code, then you will have your executable!

Original Article Here

2 comments:

Rene Pardon said...

Hi,

nice article but how would you do this with C++?
I'm searching for this a few weeks now.

regards
René (answer at boonweb.de)

Adam Gaskins said...

Check out this link:

http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044654269&id=1043284392

You could create a batch file that compiles C++ code, then execute it from within the C++ program.

I'm not a C++ programmer, so I'm probably not going to be too much help.

Post a Comment