Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- #region Additional needed Namespaces
- using System.CodeDom;
- using System.CodeDom.Compiler;
- using Microsoft.CSharp;
- #endregion
- namespace CompileViaCode
- {
- public partial class Form1 : Form
- {
- string path = "", code = "", nl = Environment.NewLine;
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- tbSave.Text = "";
- tbCode.Text = "using System;" + nl +
- "namespace Test" + nl +
- "{" + nl +
- "\tclass Prog" + nl +
- "\t{" + nl +
- "\t\tstatic void Main()" + nl +
- "\t\t{" + nl +
- "\t\t\tConsole.WriteLine(\"Hello World\");" + nl +
- "\t\t\tConsole.ReadLine();" + nl +
- "\t\t}" + nl +
- "\t}" + nl +
- "}";
- }
- private void tbSave_TextChanged(object sender, EventArgs e)
- {
- if (!tbSave.Text.EndsWith(".exe"))
- path = string.Format(Application.StartupPath + @"\Data\{0}.exe", tbSave.Text);
- else
- path = string.Format(Application.StartupPath + @"\Data\{0}", tbSave.Text);
- if (!string.IsNullOrEmpty(tbSave.Text))
- btnCompile.Enabled = true;
- else
- btnCompile.Enabled = false;
- }
- private void tbCode_TextChanged(object sender, EventArgs e)
- {
- code = tbCode.Text;
- }
- private void btnCompile_Click(object sender, EventArgs e)
- {
- #region For VS 2005:
- CSharpCodeProvider cp = new CSharpCodeProvider();
- ICodeCompiler icc = cp.CreateCompiler();
- #endregion
- #region VS 2008 or higher
- CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
- #endregion
- string sv = path;
- CompilerParameters param = new CompilerParameters();
- param.GenerateExecutable = true;
- param.OutputAssembly = sv;
- #region For VS 2005:
- CompilerResults cr = icc.CompileAssemblyFromSource(param, code);
- #endregion
- #region VS 2008 or higher
- CompilerResults res = codeProvider.CompileAssemblyFromSource(param, code);
- #endregion
- string err = "";
- if (cr.Errors.Count > 0)
- {
- foreach (CompilerError er in cr.Errors)
- err += "Line: " + er.Line + nl +
- "Error Nr: " + er.ErrorNumber + nl +
- "Msg: " + er.ErrorText + nl + nl;
- MessageBox.Show(err, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- else
- {
- err += "Build Successful." + nl + "You like to start?";
- if (MessageBox.Show(err, "Success", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
- System.Diagnostics.Process.Start(path);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement