Import code from VB.NET text

Is it possible to import text as code and then add it to sub in vb.net? If I have a .txt file filled with code, can I import it programmatically (with a button)?

I need vb.net to take this script (txt file) and use it to declare variables and create functions / subs - which is what I need.

+3


source to share


1 answer


You can do things like this using CodeDom objects. CodeDom objects allow you to dynamically generate assemblies at runtime. For example, if you create an interface

Public Interface IScript
    Property Variable1 As String
    Sub DoWork()
End Interface

      

Then you create a method like:

Imports Microsoft.VisualBasic
Imports System.CodeDom.Compiler

' ...

Public Function GenerateScript(code As String) As IScript
    Using provider As New VBCodeProvider()
        Dim parameters As New CompilerParameters()
        parameters.GenerateInMemory = True
        parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location)
        Dim interfaceNamespace As String = GetType(IScript).Namespace
        Dim codeArray() As String = New String() {"Imports " & interfaceNamespace & Environment.NewLine & code}
        Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, codeArray)
        If results.Errors.HasErrors Then
            Throw New Exception("Failed to compile script")
        Else
            Return CType(results.CompiledAssembly.CreateInstance("Script"), IScript)
        End If
    End Using
End Function

      



Now you can call it like this:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim builder As New StringBuilder()
    builder.AppendLine("Public Class Script")
    builder.AppendLine("    Implements IScript")
    builder.AppendLine("    Public Property Variable1 As String Implements IScript.Variable1")
    builder.AppendLine("    Public Sub DoWork() Implements IScript.DoWork")
    builder.AppendLine("        Variable1 = ""Hello World""")
    builder.AppendLine("    End Sub")
    builder.AppendLine("End Class")
    Dim script As IScript = GenerateScript(builder.ToString())
    script.DoWork()
    MessageBox.Show(script.Variable1) ' Displays "Hello World"
End Sub

      

Obviously, instead of generating code in a string builder, you can load it from a text file, like this:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim script As IScript = GenerateScript(File.ReadAllText("C:\script.txt")
    script.DoWork()
    MessageBox.Show(script.Variable1) ' Displays "Hello World"
End Sub

      

+2


source







All Articles