Sample code to dynamically compile the C# source code and generate the Exe/DLL. You can write the code at runtime and execute or make a DLL.
Namespace :
using System.CodeDom.Compiler;
Code:
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string Output = "Out.exe";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
//parameters.GenerateExecutable = true; // set to false to generate DLL.
parameters.OutputAssembly = Output;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, txtSource.Text);
if (results.Errors.Count > 0)
{
txtStatus.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
txtStatus.Text = txtStatus.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
txtStatus.ForeColor = Color.Blue;
txtStatus.Text = "Success";
//Launch our EXE
Process.Start(Output);
}
Namespace :
using System.CodeDom.Compiler;
Code:
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string Output = "Out.exe";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
//parameters.GenerateExecutable = true; // set to false to generate DLL.
parameters.OutputAssembly = Output;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, txtSource.Text);
if (results.Errors.Count > 0)
{
txtStatus.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
txtStatus.Text = txtStatus.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
txtStatus.ForeColor = Color.Blue;
txtStatus.Text = "Success";
//Launch our EXE
Process.Start(Output);
}