简体   繁体   中英

How do I programmatically compile a C# Windows Forms App from a richtextbox? C#

I am trying to do a Visual Studio kind of program, which allows you to type code into a RichTextBox. After pressing F5(Compile), it would compile the code. How would the user compile said code? I know how to use the ConsoleApplication Compiler, but not compiling Windows Forms:(

Could someone help? A code-example is preferable, but at this point, I'll accept ANYTHING!

My current code for Console Apps is this:

        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
        ICodeCompiler icc = codeProvider.CreateCompiler();
        string Output = "MCCACOut.exe";
            Button ButtonObject = (Button)sender;

            richTextBox201.Text = "";
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            //Make sure we generate an EXE, not a DLL
            parameters.GenerateExecutable = true;
            parameters.OutputAssembly = Output;
            CompilerResults results = icc.CompileAssemblyFromSource(parameters, richTextBox301.Text);

            if (results.Errors.Count > 0)
            {
                richTextBox201.ForeColor = Color.Red;
                foreach (CompilerError CompErr in results.Errors)
                {
                    richTextBox201.Text = richTextBox201.Text +
                                "Line number " + CompErr.Line +
                                ", Error Number: " + CompErr.ErrorNumber +
                                ", '" + CompErr.ErrorText + ";" +
                                Environment.NewLine + Environment.NewLine;
                }
            }
            else
            {
                //Successful Compile
                richTextBox201.ForeColor = Color.Blue;
                richTextBox201.Text = "Success!";
                //If we clicked run then launch our EXE
                Process.Start(Output);
            }

Could anyone convert this to compile WinForms instead of ConsoleApp? :)

I think you have to save your file with .cs extension and invoke a process to compile it using c# compiler csc.exe .

After saving the file, you can compile the code using,

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe [options] filename.cs

Take a look at this for options

You can invoke a process to do this from your IDE.

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe filename.cs";
process.StartInfo = startInfo;
process.Start();

Hope this helps.

Finally, after many, many times of struggling, I got it to work:) With the help of Nishan Chathuranga

        string compiledOutput = "Generated.exe";

        //COMPILATION WORK
        String[] referenceAssemblies = { "System.dll", "System.Drawing.dll", "System.Windows.Forms.dll" };

        CodeDomProvider _CodeCompiler = CodeDomProvider.CreateProvider("CSharp");
        System.CodeDom.Compiler.CompilerParameters _CompilerParameters =
         new System.CodeDom.Compiler.CompilerParameters(referenceAssemblies, "");

        _CompilerParameters.OutputAssembly = compiledOutput;
        _CompilerParameters.GenerateExecutable = true;
        _CompilerParameters.GenerateInMemory = false;
        _CompilerParameters.WarningLevel = 3;
        _CompilerParameters.TreatWarningsAsErrors = true;
        _CompilerParameters.CompilerOptions = "/optimize /target:winexe";//!! HERE IS THE SOLUTION !!

        string _Errors = null;
        try
        {
            // Invoke compilation
            CompilerResults _CompilerResults = null;
            _CompilerResults = _CodeCompiler.CompileAssemblyFromSource(_CompilerParameters, richTextBox1.Text);

            if (_CompilerResults.Errors.Count > 0)
            {
                // Return compilation errors
                _Errors = "";
                foreach (System.CodeDom.Compiler.CompilerError CompErr in _CompilerResults.Errors)
                {
                    _Errors += "Line number " + CompErr.Line +
                    ", Error Number: " + CompErr.ErrorNumber +
                    ", '" + CompErr.ErrorText + ";\r\n\r\n";
                }
            }
        }
        catch (Exception _Exception)
        {
            // Error occurred when trying to compile the code
            _Errors = _Exception.Message;
        }



        //AFTER WORK
        if (_Errors == null)
        {
            // lets run the program
            MessageBox.Show(compiledOutput + " Compiled !");
            System.Diagnostics.Process.Start(compiledOutput);
        }
        else
        {
            MessageBox.Show("Error occurred during compilation : \r\n" + _Errors);
        }
  • This works like a charm!

If you want to only convert the below code to windowsformapp, you can try the following code to see if it works well.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    [Obsolete]
    private void button1_Click(object sender, EventArgs e)
    {
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
        ICodeCompiler icc = codeProvider.CreateCompiler();
        string Output = "MCCACOut.exe";
        Button ButtonObject = (Button)sender;

        richTextBox1.Text = "";
        System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
        //Make sure we generate an EXE, not a DLL
        parameters.GenerateExecutable = true;
        parameters.OutputAssembly = Output;
        CompilerResults results = icc.CompileAssemblyFromSource(parameters, richTextBox2.Text);

        if (results.Errors.Count > 0)
        {
            richTextBox1.ForeColor = Color.Red;
            foreach (CompilerError CompErr in results.Errors)
            {
                richTextBox1.Text = richTextBox1.Text +
                            "Line number " + CompErr.Line +
                            ", Error Number: " + CompErr.ErrorNumber +
                            ", '" + CompErr.ErrorText + ";" +
                            Environment.NewLine + Environment.NewLine;
            }
        }
        else
        {
            //Successful Compile
            richTextBox1.ForeColor = Color.Blue;
            richTextBox1.Text = "Success!";
            //If we clicked run then launch our EXE
            Process.Start(Output);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM