I am trying out some on the fly code compilation using the VBCodeProvider
class. What I want to be able to do is modify a public variable in my assembly in the code.
I have a Public TestString As String = ""
in my application.
This is the code I am using to compile:
Dim codeProvider As New VBCodeProvider()
Dim optParams As New CompilerParameters
optParams.ReferencedAssemblies.Add("MyAssembly.exe")
optParams.ReferencedAssemblies.Add("system.windows.forms.dll")
optParams.CompilerOptions = "/t:library"
optParams.GenerateInMemory = True
Dim results As CompilerResults = codeProvider.CompileAssemblyFromSource(optParams, RichTextBox1.Text)
If results.Errors.Count > 0 Then
Dim sb As New StringBuilder("Compilation Failed with the following error(s)" + CR_LF + CR_LF)
For Each CompErr As CompilerError In results.Errors
sb.Append(String.Format("Line {0} - {1} ({2}){3}", CompErr.Line, CompErr.ErrorText, CompErr.ErrorNumber, CR_LF))
Next
MessageBox.Show(sb.ToString, "Compile Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim assy As System.Reflection.Assembly = results.CompiledAssembly
Dim exeinstance As Object = assy.CreateInstance("Script")
Dim typ As Type = exeinstance.GetType
Dim method As MethodInfo = typ.GetMethod("Main")
method.Invoke(exeinstance, Nothing)
End If
This is the code in my textbox:
Imports System
Imports MyAssembly
Class Script
Sub Main()
TestString="foo"' <-- This line fails compilation
End Sub
End Class
The error I get is 'TestString' is not declared. It may be inaccessible due to its protection level. (BC30451)