Introduction

In this article I have shared a piece of code which will compile a block of C# code passed as an argument (source) to the function and generate a DLL or EXE at runtime from an C# Application.

If any compilation error occurs, the error information will be displayed in a message box.

Namespace references to be added to the code to make the function work

1.using Microsoft.CSharp;
2.using System.CodeDom.Compiler;

Function

01.bool GenerateAssembly(string source, string filePath, string asmType)
02.{
03.if (String.IsNullOrEmpty(source))
04. return false;
05.
06.bool isAsmGenerated = false;
07.CodeDomProvider provider = null;
08.CompilerParameters parameters = null;
09.
10.try
11.{
12. provider = CodeDomProvider.CreateProvider("CSharp");
13. if (provider != null)
14. {
15. parameters = new CompilerParameters();
16. parameters.GenerateExecutable = true;
17. parameters.OutputAssembly = filePath;
18. if (asmType == "dll")
19. parameters.CompilerOptions = " /target:library ";
20. else
21. parameters.CompilerOptions = " /target:exe ";
22. CompilerResults results = provider.CompileAssemblyFromSource(parameters, source);
23. if (results.Errors.Count > 0)
24. {
25. StringBuilder sbErrors = new StringBuilder();
26. foreach (CompilerError err in results.Errors)
27. {
28. sbErrors.Append(err.ErrorNumber + ":" + err.ErrorText + "\t Line:" + err.Line + "\n");
29. }
30.
31. MessageBox.Show(sbErrors.ToString(), "Compile Errors", MessageBoxButtons.OK, MessageBoxIcon.Stop);
32. isAsmGenerated = false;
33. }
34. else
35. isAsmGenerated = true;
36.
37. results = null;
38. }
39. else
40. isAsmGenerated = false;
41.
42.}
43.catch (Exception ex)
44.{
45. MessageBox.Show(ex.Message, "Compile Errors", MessageBoxButtons.OK, MessageBoxIcon.Stop);
46. isAsmGenerated = false;
47.}
48.finally
49.{
50. parameters = null;
51. if (provider != null)
52. provider.Dispose();
53. provider = null;
54.}
55.return isAsmGenerated;
56.}

Arguments

1) source - Source code in C# format, which needs to be compiled
2) filePath - Full file path with file name (.dll or .exe), where exactly it has to be created.
3) asmType - Type of Assembly. Whether EXE or DLL to be generated.