How to programmatically compile code by using the Visual Basic .NET or Visual Basic 2005 compiler (304654)



The information in this article applies to:

  • Microsoft .NET Framework 1.0
  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

This article was previously published under Q304654
For a Microsoft Visual C# .NET version of this article, see 304655.

This article refers to the following Microsoft .NET Framework Class Library namespace:
  • System.CodeDom.Compiler

SUMMARY

The .NET Framework exposes classes that allow you to programmatically access the Visual Basic .NET or Visual Basic 2005 language compiler. This might also be useful if you want to write your own code-compiling utilities. This article provides sample code that allows you to compile code from a text source. The application allows you to either just build the executable or build the executable and run it. Any errors that occur during the compilation process are displayed on the form.

MORE INFORMATION

Step 1: Requirements

  • Visual Studio .NET or Visual Studio 2005
  • Visual Basic .NET Language Compiler or Visual Basic 2005 Language Compiler

Step 2: How to Programmatically Compile Code

The .NET Framework provides the ICodeCompiler compiler execution interface. VBCodeProvider class implements this interface and provides access to instances of the Visual Basic code generator and code compiler. The following sample creates an instance of the VBCodeProvider and uses it to get a reference to a ICodeCompiler interface.

Dim codeProvider As New VBCodeProvider()
Dim icc As ICodeCompiler = codeProvider.CreateCompiler
				

Once you have a reference to an ICodeCompiler interface, you can use it to compile your source code. You pass parameters to the compiler by using the CompilerParameters class. Here is an example:
Dim parameters As New CompilerParameters()
Dim results As CompilerResults

parameters.GenerateExecutable = True
parameters.OutputAssembly = Output
results = icc.CompileAssemblyFromSource(parameters, SourceText)
				

The code above uses the CompilerParameters object to tell the compiler that you want to generate an executable file (as opposed to a DLL) and that you want to output the resulting assembly to disk. The call to CompileAssemblyFromSource is where your assembly gets compiled. This method takes your parameters object and the source code, which is a string. Once you compile your code you can check to see if there were any compilation errors. We use the return value from CompileAssemblyFromSource, which is a CompilerResults object. This object contains an errors collection, which contains any errors that occurred during the compile.
If results.Errors.Count > 0 Then
   'There were compiler errors
   Dim CompErr As CompilerError
   For Each CompErr In results.Errors
      textBox2.Text = textBox2.Text & _
                      "Line number " & CompErr.Line & _
                      ", Error Number: " & CompErr.ErrorNumber & _
                      ", '" & CompErr.ErrorText & ";" & _
      Environment.NewLine & Environment.NewLine
   Next
End If

				

There are other options for compiling, such as compiling from a file. You can also batch compile, which means you can compile multiple files or sources at the same time. Additional information on these classes is available on MSDN Online:

Step 3: Step-by-Step Sample

  1. Create a new Visual Basic .NET or Visual Basic 2005 Windows Application. Form1 is created by default.
  2. In the Code View window of Form1, replace all of the existing text with the following code:
    Option Strict On
    Imports System.CodeDom.Compiler
    
    
    Public Class Form1
        Inherits System.Windows.Forms.Form
    
    #Region " Windows Form Designer generated code "
    
        Public Sub New()
            MyBase.New()
    
            'This call is required by the Windows Form Designer.
            InitializeComponent()
    
            'Add any initialization after the InitializeComponent() call
    
        End Sub
    
        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub
        Friend WithEvents textBox1 As System.Windows.Forms.TextBox
        Friend WithEvents button1 As System.Windows.Forms.Button
        Friend WithEvents textBox2 As System.Windows.Forms.TextBox
        Friend WithEvents button2 As System.Windows.Forms.Button
    
        'Required by the Windows Form Designer
        Private components As System.ComponentModel.Container
    
        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.textBox2 = New System.Windows.Forms.TextBox()
            Me.textBox1 = New System.Windows.Forms.TextBox()
            Me.button1 = New System.Windows.Forms.Button()
            Me.button2 = New System.Windows.Forms.Button()
            Me.SuspendLayout()
            '
            'textBox2
            '
            Me.textBox2.BackColor = System.Drawing.SystemColors.Control
            Me.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.None
            Me.textBox2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.textBox2.ForeColor = System.Drawing.SystemColors.WindowText
            Me.textBox2.Location = New System.Drawing.Point(264, 56)
            Me.textBox2.Multiline = True
            Me.textBox2.Name = "textBox2"
            Me.textBox2.Size = New System.Drawing.Size(240, 232)
            Me.textBox2.TabIndex = 2
            Me.textBox2.Text = ""
            '
            'textBox1
            '
            Me.textBox1.Location = New System.Drawing.Point(16, 48)
            Me.textBox1.Multiline = True
            Me.textBox1.Name = "textBox1"
            Me.textBox1.Size = New System.Drawing.Size(240, 240)
            Me.textBox1.TabIndex = 0
            Me.textBox1.Text = "textBox1"
            '
            'button1
            '
            Me.button1.Location = New System.Drawing.Point(368, 304)
            Me.button1.Name = "button1"
            Me.button1.TabIndex = 1
            Me.button1.Text = "Build"
            '
            'button2
            '
            Me.button2.Location = New System.Drawing.Point(456, 304)
            Me.button2.Name = "button2"
            Me.button2.TabIndex = 1
            Me.button2.Text = "Run"
            '
            'Form1
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(544, 333)
            Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.button2, Me.textBox1, Me.button1, Me.textBox2})
            Me.Name = "Form1"
            Me.Text = "Form1"
            Me.ResumeLayout(False)
    
        End Sub
    
    #End Region
    
        Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click, button2.Click
            Dim codeProvider As New VBCodeProvider()
            Dim icc As ICodeCompiler = codeProvider.CreateCompiler
            Dim Output As String = "Out.exe"
            Dim ButtonObject As Button = CType(sender, Button)
    
            textBox2.Text = ""
            Dim parameters As New CompilerParameters()
            Dim results As CompilerResults
            'Make sure we generate an EXE, not a DLL
            parameters.GenerateExecutable = True
            parameters.OutputAssembly = Output
            results = icc.CompileAssemblyFromSource(parameters, textBox1.Text)
    
            If results.Errors.Count > 0 Then
                'There were compiler errors
                textBox2.ForeColor = Color.Red
                Dim CompErr As CompilerError
                For Each CompErr In results.Errors
                    textBox2.Text = textBox2.Text & _
                    "Line number " & CompErr.Line & _
                    ", Error Number: " & CompErr.ErrorNumber & _
                    ", '" & CompErr.ErrorText & ";" & _
                    Environment.NewLine & Environment.NewLine
                Next
            Else
                'Successful Compile
                textBox2.ForeColor = Color.Blue
                textBox2.Text = "Success!"
                'If we clicked run then launch the EXE
                If ButtonObject.Text = "Run" Then Process.Start(Output)
            End If
    
        End Sub
    
    End Class
    					
    Note The code should be changed in Visual Basic 2005. If you create a new form that is named Form1 in Visual Basic 2005, you have a Form1.vb file for your code and a Form1.Designer.vb file that contains the automatically generated part. The Windows Forms Designer uses the partial keyword to divide the implementation of Form1 into two separate files. This prevents the designer-emitted code from being interspersed with your code. For more information about the Visual Basic 2005 language enhancements, visit the following Microsoft Web site: For more information about partial classes and the Windows Forms Designer, visit the following Microsoft Web site:
  3. Run the project. After Form1 loads, click the Build button. Notice that you get a couple of compiler errors.
  4. Next, copy the following code into the textbox, replacing any existing text:
    Imports System
    
    Module Module1
    
        Sub Main()
            Console.WriteLine("Hello World!")
            Console.WriteLine("Press ENTER")
            Console.ReadLine()
        End Sub
    
    End Module
    					
  5. Click Build again. The compile should be successful.
  6. Click Run and it will compile the code and run the resulting executable file. The compile creates a executable file called "Out.exe" in the same folder as the application that you are running.

    NOTE: You can modify code in the textbox to see different compiler errors. For example, delete one of the parenthesis and rebuild the code.
  7. Lastly, modify the code in the textbox to output another line of text to the console window. Click Run to see the output.

Modification Type:MinorLast Reviewed:10/3/2006
Keywords:kbvs2005applies kbvs2005swept kbBCL kbCompiler kbhowto kbProd2Web KB304654 kbAudDeveloper