Visual Basic Code Snippet - Compile C# or VB source code run-time
(VB) Visual Basic 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:
Visual Basic Code Snippet - Compile C# or VB source code run-time
This .Net Visual Basic 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 Function CompileCode(ByVal _CodeProvider As System.CodeDom.Compiler.CodeDomProvider, ByVal _SourceCode As String, ByVal _SourceFile As String, ByVal _ExeFile As String, ByVal _AssemblyName As String, ByVal _ResourceFiles() As String, ByRef _Errors As String) As Boolean ' set interface for compilation Dim _CodeCompiler As System.CodeDom.Compiler.ICodeCompiler = _CodeProvider.CreateCompiler() ' Define parameters to invoke a compiler Dim _CompilerParameters As New System.CodeDom.Compiler.CompilerParameters() If _ExeFile IsNot Nothing Then ' Set the assembly file name to generate. _CompilerParameters.OutputAssembly = _ExeFile ' Generate an executable instead of a class library. _CompilerParameters.GenerateExecutable = True _CompilerParameters.GenerateInMemory = False ElseIf _AssemblyName IsNot Nothing Then ' 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 End If ' 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 IsNot Nothing AndAlso _ResourceFiles.Length > 0 Then For Each _ResourceFile As String In _ResourceFiles ' Set the embedded resource file of the assembly. _CompilerParameters.EmbeddedResources.Add(_ResourceFile) Next _ResourceFile End If Try ' Invoke compilation Dim _CompilerResults As System.CodeDom.Compiler.CompilerResults = Nothing If _SourceFile IsNot Nothing AndAlso System.IO.File.Exists(_SourceFile) Then ' soruce code in external file _CompilerResults = _CodeCompiler.CompileAssemblyFromFile(_CompilerParameters, _SourceFile) Else ' source code pass as a string _CompilerResults = _CodeCompiler.CompileAssemblyFromSource(_CompilerParameters, _SourceCode) End If If _CompilerResults.Errors.Count > 0 Then ' Return compilation errors _Errors = "" For Each CompErr As System.CodeDom.Compiler.CompilerError In _CompilerResults.Errors _Errors &= "Line number " & CompErr.Line & ", Error Number: " & CompErr.ErrorNumber & ", '" & CompErr.ErrorText & ";" & Constants.vbCrLf & Constants.vbCrLf Next CompErr ' Return the results of compilation - Failed Return False Else ' no compile errors _Errors = Nothing End If Catch _Exception As Exception ' Error occurred when trying to compile the code _Errors = _Exception.Message Return False End Try ' Return the results of compilation - Success Return True End Function
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
Dim _Errors As String = "" ' C# source code pass as a string Dim _CSharpSourceCode As String = "using System;" & _ ControlChars.CrLf & ControlChars.CrLf & _ "namespace test" & ControlChars.CrLf & "{" & _ ControlChars.CrLf & "class Program" & _ ControlChars.CrLf & "{" & _ ControlChars.CrLf & "static void Main(string[] args)" & _ ControlChars.CrLf & "{" & ControlChars.CrLf & _ "Console.WriteLine(""Press ENTER key to start ..."");" & _ ControlChars.CrLf & "Console.ReadLine();" & _ ControlChars.CrLf & "for (int c=0; c<=100; c++)" & _ ControlChars.CrLf & "Console.WriteLine(c.ToString());" & _ ControlChars.CrLf & "}" & ControlChars.CrLf & _ "}" & ControlChars.CrLf & "}" ' Compile C-Sharp code If CompileCode(New Microsoft.CSharp.CSharpCodeProvider(), _CSharpSourceCode, Nothing, "c:\temp\C-Sharp-test.exe", Nothing, Nothing, _Errors) Then Console.WriteLine("Code compiled successfully") Else Console.WriteLine("Error occurred during compilation : " & Constants.vbCrLf & _Errors) End If
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
Dim _Errors As String = "" ' VB source code pass as a string Dim _VBSourceCode As String = "Imports System" & _ ControlChars.CrLf & ControlChars.CrLf & _ "Namespace test" & ControlChars.CrLf & _ "Friend Class Program" & ControlChars.CrLf & _ "Shared Sub Main(ByVal args() As String)" & _ ControlChars.CrLf & _ "Console.WriteLine(""Press ENTER key to start ..."")" & _ ControlChars.CrLf & "Console.ReadLine()" & _ ControlChars.CrLf & "For c As Integer = 0 To 100" & _ ControlChars.CrLf & "Console.WriteLine(c.ToString())" & _ ControlChars.CrLf & "Next c" & ControlChars.CrLf & _ "End Sub" & ControlChars.CrLf & _ "End Class" & ControlChars.CrLf & _ "End Namespace" ' compile visual basic code If CompileCode(New Microsoft.VisualBasic.VBCodeProvider(), _VBSourceCode, Nothing, "c:\temp\VB-test.exe", Nothing, Nothing, _Errors) Then Console.WriteLine("Code compiled successfully") Else Console.WriteLine("Error occurred during compilation : " & Constants.vbCrLf & _Errors) End If
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.
' Compile C-Sharp code If CompileCode(New Microsoft.CSharp.CSharpCodeProvider(), Nothing, "c:\temp\test.cs", "c:\temp\C-Sharp-test.exe", Nothing, Nothing, _Errors) Then 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 : " & Constants.vbCrLf & _Errors) End If ' compile visual basic code If CompileCode(New Microsoft.VisualBasic.VBCodeProvider(), Nothing, "c:\temp\test.vb", "c:\temp\VB-test.exe", Nothing, Nothing, _Errors) Then Console.WriteLine("Code compiled successfully") Else Console.WriteLine("Error occurred during compilation : " & Constants.vbCrLf & _Errors) End If
VB Keywords Used:
- System.CodeDom.Compiler
- CodeDomProvider
- CompilerResults
- CompilerParameters
- CompilerOptions
- Exception
Code Snippet Information:
- Applies To: Visual Studio, .Net, CLI, VB, Visual Basic, Compiler, Microsoft.CSharp, Microsoft.VisualBasic, System.CodeDom.Compiler, Programmatically compile code, Run-Time Code Generation
- Programming Language : VB (Visual Basic)
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
francisco perez :: May 31-2010 :: 08:59 PM
Hi
I'm looking the way to create an VB app which I can set the folder at the time I'm running it
like for example My app(vb program) "c:\music" (parameter) this will run the My application and it will take c:\music as the current folder
And or create my (vb app) the add it to the right click of my mouse the when I run it it will run on the folder that I'm pointing with the mouse at that specific moment.
Do you have any idea how I can do it
Thanks