CodeCompiler.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.IO;
  3. using Microsoft.CSharp;
  4. using System.CodeDom.Compiler;
  5. using System.Reflection;
  6. namespace csharp_tests
  7. {
  8. public class CodeCompiler
  9. {
  10. protected CSharpCodeProvider compiler = new CSharpCodeProvider();
  11. protected CompilerParameters compiler_parameters;
  12. public CodeCompiler()
  13. {
  14. this.compiler_parameters = new CompilerParameters
  15. {
  16. WarningLevel = 0,
  17. GenerateExecutable = false,
  18. GenerateInMemory = true/*,
  19. OutputAssembly = "Assembly.dll"*/
  20. };
  21. }
  22. public void AddReferencedAssembly(string name)
  23. {
  24. this.compiler_parameters.ReferencedAssemblies.Add(name);
  25. }
  26. public Assembly compileFile(string file)
  27. {
  28. Assembly returnAssembly = null;
  29. try
  30. {
  31. CompilerResults results = this.compiler.CompileAssemblyFromFile(compiler_parameters, file);
  32. returnAssembly = results.CompiledAssembly;
  33. foreach (string output in results.Output)
  34. {
  35. Console.WriteLine(output);
  36. }
  37. }
  38. catch (Exception exception)
  39. {
  40. Console.WriteLine(exception.Message);
  41. }
  42. return returnAssembly;
  43. }
  44. }
  45. }