user2023328
user2023328

Reputation: 125

Import code from text VB.NET

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

What I need is to make vb.net to accept that script (txt file), and use it to declare variables and make functions/subs - that's all I need to.

Upvotes: 3

Views: 4938

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

You can do this kind of thing using the CodeDom objects. The CodeDom objects allow you to dynamically generate assemblies at run-time. For instance, if you make an interface

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

Then, you create a method, like this:

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 building the code in a string builder, you could load it out of 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

Upvotes: 3

Related Questions