public static Assembly CompileCode(string code, string FileName, out CompilerResults result, string[] resourceFilePaths = null) { Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net) if (FileName != null) { options.OutputAssembly = FileName; } else { options.GenerateInMemory = true; } // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows // thus they can only do the things you want them to. // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it) // Just to avoid bloating this example to much, we will just add THIS program to its references, that way we don't need another // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to // the "script" //var assemblies = AppDomain.CurrentDomain // .GetAssemblies() // .Where(a => !a.IsDynamic) // .Select(a => a.Location); //options.ReferencedAssemblies.AddRange(assemblies.ToArray()); options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); ReferencedAssemblies.ForEach(x => options.ReferencedAssemblies.Add(x)); //options.ReferencedAssemblies.Add("System.Data.dll"); //options.ReferencedAssemblies.Add("System.dll"); //options.ReferencedAssemblies.Add("System.Xml.dll"); //options.ReferencedAssemblies.Add("System.Data.Linq.dll"); //options.ReferencedAssemblies.Add("ChampionshipSolutions.DM.dll"); //options.ReferencedAssemblies.Add("mscorlib.dll"); //options.ReferencedAssemblies.Add("System.Core.dll"); if (resourceFilePaths != null) { foreach (string filePath in resourceFilePaths) { if (System.IO.File.Exists(filePath)) { options.EmbeddedResources.Add(filePath); } } } // Compile our code //CompilerResults result; result = csProvider.CompileAssemblyFromSource(options, code); if (result.Errors.HasErrors) { // TODO: report back to the user that the script has errored return(null); } if (result.Errors.HasWarnings) { // TODO: tell the user about the warnings, might want to prompt them if they want to continue // running the "script" } return(result.CompiledAssembly); }