Original Post
When i was working on this i noticed their was little information on the web in regards to creating a C# scripting engine. So i thought i would share some code i trew togther from some webblogs and personal experince that enabled a basic C# scripting engine. This code isnt that complex. What it does is uses the ICodeCompiler class in the .net framework to compile a script, give it all the assemblies in your currnet app and then run a function. You are even able to pass objects to the function in the scripting engine, allowing you to access hardcoded objects and classes.
using Microsoft.CSharp;
using System.CodeDom.Compiler;
/// <summary>
/// Loads a script file and exicutes it.
/// </summary>
/// <param name="sourcefile">the file to load the script from</param>
private Object sobj;
public void load(string sourcefile)
{
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 = "Script.Main";
parameters.IncludeDebugInformation = false;
//Add all the assemblies in the currnet application to the script.
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
parameters.ReferencedAssemblies.Add(asm.Location);
}
//Read a file
string source;
StreamReader re = File.OpenText(sourcefile);
source = re.ReadToEnd();
re.Close();
//Compile the script
CompilerResults results = compiler.CompileAssemblyFromSource(parameters, source);
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);
}
object o = results.CompiledAssembly.CreateInstance("Script");
sobj = o;
}
/// <summary>
/// Call a function from within the script
/// </summary>
/// <param name="function">the name of the function</param>
/// <param name="parm">an array of parameters</param>
public void Invoke(string function, object[] parm)
{
//if not compiled
if(sobj == null)
{
return;
}
//try to run the function
try
{
Type type = sobj.GetType();
MethodInfo m = type.GetMethod(function);
m.Invoke(sobj,parm);
}
catch{
return;
}
}
Its not the best but its a start for anyone like me who needs a basic C# scripting engine. Dave.