C# Code Snippet - Compile C# or VB source code run-time
(C-Sharp) C# code snippet compile C# or VB source code run-time from a text string or external text file and build the executable. Programmatically compile code using C#/VB compiler.
Bookmark:
C# Code Snippet - Compile C# or VB source code run-time
This .Net C# code snippet compile C# or VB source code runtime from a text string or external text file and build the executable. To use this function simply provide language (C#/VB) provider, source code in text string or as a file, output executable file name (optional), output assembly name (optional), resource files (optional), reference string to get errors.
The .NET Framework exposes classes that allow you to programmatically access the C# and VB language compilers. This might be useful if you want to write your own code-compiling utilities. This code snippet provides sample code that enables you to compile code from a text string or external text file. The code snippet allows you to build the executable. Any errors that occur during the compilation process are return as a string.
/// <summary>
/// Function to compile .Net C#/VB source codes at runtime
/// </summary>
/// <param name="_CodeProvider">Base class for compiler provider</param>
/// <param name="_SourceCode">C# or VB source code as a string</param>
/// <param name="_SourceFile">External file containing C# or VB source code</param>
/// <param name="_ExeFile">File path to create external executable file</param>
/// <param name="_AssemblyName">File path to create external assembly file</param>
/// <param name="_ResourceFiles">Required resource files to compile the code</param>
/// <param name="_Errors">String variable to store any errors occurred during the process</param>
/// <returns>Return TRUE if successfully compiled the code, else return FALSE</returns>
private bool CompileCode(System.CodeDom.Compiler.CodeDomProvider _CodeProvider, string _SourceCode, string _SourceFile, string _ExeFile, string _AssemblyName, string[] _ResourceFiles, ref string _Errors)
{
// set interface for compilation
System.CodeDom.Compiler.ICodeCompiler _CodeCompiler = _CodeProvider.CreateCompiler();
// Define parameters to invoke a compiler
System.CodeDom.Compiler.CompilerParameters _CompilerParameters =
new System.CodeDom.Compiler.CompilerParameters();
if (_ExeFile != null)
{
// Set the assembly file name to generate.
_CompilerParameters.OutputAssembly = _ExeFile;
// Generate an executable instead of a class library.
_CompilerParameters.GenerateExecutable = true;
_CompilerParameters.GenerateInMemory = false;
}
else if (_AssemblyName != null)
{
// Set the assembly file name to generate.
_CompilerParameters.OutputAssembly = _AssemblyName;
// Generate an executable instead of a class library.
_CompilerParameters.GenerateExecutable = false;
_CompilerParameters.GenerateInMemory = false;
}
else
{
// Generate an executable instead of a class library.
_CompilerParameters.GenerateExecutable = false;
_CompilerParameters.GenerateInMemory = true;
}
// Generate debug information.
//_CompilerParameters.IncludeDebugInformation = true;
// Set the level at which the compiler
// should start displaying warnings.
_CompilerParameters.WarningLevel = 3;
// Set whether to treat all warnings as errors.
_CompilerParameters.TreatWarningsAsErrors = false;
// Set compiler argument to optimize output.
_CompilerParameters.CompilerOptions = "/optimize";
// Set a temporary files collection.
// The TempFileCollection stores the temporary files
// generated during a build in the current directory,
// and does not delete them after compilation.
_CompilerParameters.TempFiles = new System.CodeDom.Compiler.TempFileCollection(".", true);
if (_ResourceFiles != null && _ResourceFiles.Length > 0)
foreach (string _ResourceFile in _ResourceFiles)
{
// Set the embedded resource file of the assembly.
_CompilerParameters.EmbeddedResources.Add(_ResourceFile);
}
try
{
// Invoke compilation
System.CodeDom.Compiler.CompilerResults _CompilerResults = null;
if (_SourceFile != null && System.IO.File.Exists(_SourceFile))
// soruce code in external file
_CompilerResults = _CodeCompiler.CompileAssemblyFromFile(_CompilerParameters, _SourceFile);
else
// source code pass as a string
_CompilerResults = _CodeCompiler.CompileAssemblyFromSource(_CompilerParameters, _SourceCode);
if (_CompilerResults.Errors.Count > 0)
{
// Return compilation errors
_Errors = "";
foreach (System.CodeDom.Compiler.CompilerError CompErr in _CompilerResults.Errors)
{
_Errors += "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";\r\n\r\n";
}
// Return the results of compilation - Failed
return false;
}
else
{
// no compile errors
_Errors = null;
}
}
catch (Exception _Exception)
{
// Error occurred when trying to compile the code
_Errors = _Exception.Message;
return false;
}
// Return the results of compilation - Success
return true;
}
Here is a simple example shows how to use above function (CompileCode) to compile a C# (C-Sharp) source code pass as a string, resulting executable file will be saved as C:\temp\ C-Sharp-test.exe
string _Errors = "";
// C# source code pass as a string
string _CSharpSourceCode = @"
using System;
namespace test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Press ENTER key to start ..."");
Console.ReadLine();
for (int c=0; c<=100; c++)
Console.WriteLine(c.ToString());
}
}
}";
// Compile C-Sharp code
if (CompileCode(new Microsoft.CSharp.CSharpCodeProvider(), _CSharpSourceCode, null, "c:\\temp\\C-Sharp-test.exe", null, null, ref _Errors))
Console.WriteLine("Code compiled successfully");
else
Console.WriteLine("Error occurred during compilation : \r\n" + _Errors);
This example shows how to use above function (CompileCode) to compile a VB (Visual Basic) source code pass as a string, resulting executable file will be saved as C:\temp\ C-Sharp-test.exe
string _Errors = "";
// VB source code pass as a string
string _VBSourceCode = @"
Imports System
Namespace test
Friend Class Program
Shared Sub Main(ByVal args() As String)
Console.WriteLine(""Press ENTER key to start ..."")
Console.ReadLine()
For c As Integer = 0 To 100
Console.WriteLine(c.ToString())
Next c
End Sub
End Class
End Namespace";
// compile visual basic code
if (CompileCode(new Microsoft.VisualBasic.VBCodeProvider(), _VBSourceCode, null, "c:\\temp\\VB-test.exe", null, null, ref _Errors))
Console.WriteLine("Code compiled successfully");
else
Console.WriteLine("Error occurred during compilation : \r\n" + _Errors);
This example shows how to use above function (CompileCode) to compile a C# and VB source code from external files C#:c:\temp\test.cs and VB:c:\temp\test.vb, resulting executable files will be saved as C#:C:\temp\C-Sharp-test.exe and VB:C:\temp\VB-test.exe, and also shows how to run the executable after creating it using Process.Start.
string _Errors = "";
// Compile C-Sharp code
if (CompileCode(new Microsoft.CSharp.CSharpCodeProvider(), null, "c:\\temp\\test.cs", "c:\\temp\\C-Sharp-test.exe", null, null, ref _Errors))
{
Console.WriteLine("Code compiled successfully");
// lets run the program
System.Diagnostics.Process.Start("c:\\temp\\C-Sharp-test.exe");
}
else
Console.WriteLine("Error occurred during compilation : \r\n" + _Errors);
// compile visual basic code
if (CompileCode(new Microsoft.VisualBasic.VBCodeProvider(), null, "c:\\temp\\test.vb", "c:\\temp\\VB-test.exe", null, null, ref _Errors))
Console.WriteLine("Code compiled successfully");
else
Console.WriteLine("Error occurred during compilation : \r\n" + _Errors);
C# Keywords Used:
- System.CodeDom.Compiler
- CodeDomProvider
- CompilerResults
- CompilerParameters
- CompilerOptions
- Exception
Code Snippet Information:
- Applies To: .Net, C#, CLI, VB, Visual Basic, Compiler, Microsoft.CSharp, Microsoft.VisualBasic, System.CodeDom.Compiler, Programmatically compile code, Run-Time Code Generation
- Programming Language : C# (C-Sharp)
External Resources:
- System.CodeDom.Compiler Namespace
- CodeDomProvider Class
- CompilerResults Class
- CompilerParameters Properties
- CompilerParameters.GenerateInMemory Property
- How to programmatically compile code using C# compiler
- Run-Time Code Generation II: Invoke Methods using System.Reflection
- Run-Time Code Generation I: Compile C#-Code using Microsoft.CSharp and System.CodeCom.Compiler
Yogesh :: May 11-2010 :: 05:19 AM
excellent code !!! for dynamic compilation
Rangi :: July 27-2010 :: 06:33 AM
Thank you.
Just what I was chasing.
All the other online examples are filled with fluff. Yours is succinct.
Thanks again.
asd :: September 21-2010 :: 09:27 AM
how can i set the output file to be dll file, so that , for example, the current program that called the compilation will be able to call a function from the compiled code, or even create new class instances from there?
is it even possible?
qualarella :: February 22-2011 :: 11:23 PM
Ohh - Thanks! - It is really important information for me - :) You helped me