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)
Return CType(results.CompiledAssembly.CreateInstance("Script"), IScript)
End Using
End Function
我正在使用上面的代码来运行可能随时间变化的字符串。然而,当我运行它时,我收到此错误:
System.IO.FileNotFoundException: 'Could not load file or assembly 'file:///C:\Users\zjf\AppData\Local\Temp\ykujgxkp.dll' or one of its dependencies. The system cannot find the file specified.'
我不知道如何解决这个问题。有人可以帮我吗?
谢谢!
答案 0 :(得分:0)
您错过了必须在应用程序中实施dll
文件的部分,请尝试将其添加到您的代码中:
Parameters.EmbeddedResources.Add("C:\Users\zjf\AppData\Local\Temp\ykujgxkp.dll")
Parameters.ReferencedAssemblies.AddRange(New String() {"System.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.Management.dll", "C:\Users\zjf\AppData\Local\Temp\ykujgxkp.dll"})
所以你的最终代码应该是这样的:
Public Function GenerateScript(code As String) As IScript
Using provider As New VBCodeProvider()
Dim parameters As New CompilerParameters()
parameters.GenerateInMemory = True
Parameters.EmbeddedResources.Add("C:\Users\zjf\AppData\Local\Temp\ykujgxkp.dll")
Parameters.ReferencedAssemblies.AddRange(New String() {"System.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.Management.dll", "C:\Users\zjf\AppData\Local\Temp\ykujgxkp.dll"})
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)
Return CType(results.CompiledAssembly.CreateInstance("Script"), IScript)
End Using
End Function