There's a great example here with source code provided. Essentially you create a runner that's an exe that executes your cs file.
The runner is a console application. You just pass your CS file in as a parameter. One caveat is that you have to name your class "CSScript". But it would look like the following class. The link uses the CSharpCodeProvider class to compile your source code on the fly.
using System;
using System.Windows.Forms;
class CScript {
public void Main() {
// your dynamic code here
}
}
The example executes the source by dynamically compiling the cs file passed in and then uses reflection to invoke the Main Method.
void ExecuteSource(String sourceText) {
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler compiler = codeProvider.CreateCompiler();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
parameters.OutputAssembly = "CS-Script-Tmp-Junk";
parameters.MainClass = "CScript.Main";
parameters.IncludeDebugInformation = false;
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {
parameters.ReferencedAssemblies.Add(asm.Location);
}
CompilerResults results = compiler.CompileAssemblyFromSource(parameters, sourceText);
if (results.Errors.Count > 0) {
string errors = "Compilation failed:\n";
foreach (CompilerError err in results.Errors) {
errors += err.ToString() + "\n";
}
MessageBox.Show(errors, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} else {
object o = results.CompiledAssembly.CreateInstance("CScript");
Type type = o.GetType();
MethodInfo m = type.GetMethod("Main");
m.Invoke(o, null);
if (File.Exists("CS-Script-Tmp-Junk")) { File.Delete("CS-Script-Tmp-Junk"); }
}
}
To call you run a command as follows
CS-SCript.exe yourcsfile.cs