Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.CodeDom.Compiler;
- using System.Collections.Generic;
- using System.Reflection;
- using System.Text.RegularExpressions;
- public class CSharpCompiler
- {
- public CSharpCompiler(string code)
- {
- this.Initialize();
- this.Code = code;
- }
- private void Initialize()
- {
- this.Parameters = new CompilerParameters();
- this.Parameters.GenerateInMemory = true;
- this.Parameters.IncludeDebugInformation = false;
- this.Parameters.GenerateExecutable = false;
- this.References = new List<string>();
- this.Results = default(CompilerResults);
- this.Code = null;
- }
- public string Code { get; private set; }
- private CompilerParameters Parameters { get; set; }
- public List<string> References { get; private set; }
- public CompilerResults Results { get; private set; }
- public bool CompileInMemory()
- {
- return (this.CompileInMemory(null));
- }
- public bool CompileInMemory(object[] args)
- {
- return (this.CompileInMemory(args, false));
- }
- public bool CompileInMemory(object[] args, bool referenceFix)
- {
- try
- {
- this.RemoveDuplicateReferences();
- foreach (string reference in this.References)
- this.Parameters.ReferencedAssemblies.Add(reference);
- this.Results = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(this.Parameters, this.Code);
- if (this.Results.Errors.Count == 0)
- {
- Type[] resultTypes = this.Results.CompiledAssembly.GetTypes();
- object o = this.Results.CompiledAssembly.CreateInstance(resultTypes[0].FullName);
- MethodInfo[] m = resultTypes[0].GetMethods();
- m[0].Invoke(o, args);
- return (true);
- }
- else
- {
- if (referenceFix)
- {
- string refError = "You must add a reference to assembly";
- List<string> newReferences = new List<string>();
- foreach (CompilerError error in this.Results.Errors)
- {
- Match m = Regex.Match(error.ErrorText, (refError + " '.*?,"), RegexOptions.Singleline);
- if (!String.IsNullOrEmpty(m.Value))
- newReferences.Add(m.Value.Replace((refError + " '"), "").Replace(",", "") + ".dll");
- }
- this.References.AddRange(newReferences);
- return (this.CompileInMemory(args, (newReferences.Count > 0)));
- }
- else
- return (false);
- }
- }
- catch
- {
- return (false);
- }
- finally
- {
- this.Parameters.ReferencedAssemblies.Clear();
- }
- }
- private void RemoveDuplicateReferences()
- {
- List<string> goodReferences = new List<string>();
- foreach (string reference in this.References)
- {
- if (!goodReferences.Contains(reference))
- goodReferences.Add(reference);
- }
- this.References = goodReferences;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement