【发布时间】:2011-06-21 17:12:16
【问题描述】:
我需要创建一个 VB.NET 函数,它获取 VB.NET 控制台应用程序的源代码并将其编译成 控制台应用程序。
例如,这是控制台应用程序的 VB.NET 源代码:
Module Module1
Sub Main()
Dim UserInfo As String = "Name: User1"
System.Console.WriteLine(UserInfo)
System.Console.ReadLine()
End Sub
End Module
到目前为止我的代码:
Friend Function CreateConsoleApplication(ByVal VBSourceCode As String, ByVal WhereToSave As String) As Boolean
Try
'now compile the source code contained in
'VBSourceCode string variable
Catch ex As Exception
MessageBox.Show(ex.ToString)
Return False
End Try
End Function
更新:这是解决方案:-
Friend Function CreateConsoleApplication(ByVal VBSourceCode As String, ByVal WhereToSave As String) As Boolean
Try
VBSourceCode = "Module Module1" & vbCrLf & "Sub Main()" & vbCrLf & "Dim UserInfo As String = ""Name: User1""" & vbCrLf & "System.Console.WriteLine(UserInfo)" & vbCrLf & "System.Console.ReadLine()" & vbCrLf & "End Sub" & vbCrLf & "End Module"
WhereToSave = "E:\TestConsole.exe"
Dim provider As Microsoft.VisualBasic.VBCodeProvider
Dim compiler As System.CodeDom.Compiler.ICodeCompiler
Dim params As System.CodeDom.Compiler.CompilerParameters
Dim results As System.CodeDom.Compiler.CompilerResults
params = New System.CodeDom.Compiler.CompilerParameters
params.GenerateInMemory = False
params.TreatWarningsAsErrors = False
params.WarningLevel = 4
'Put any references you need here - even you own dll's, if you want to use one
Dim refs() As String = {"System.dll", "Microsoft.VisualBasic.dll"}
params.ReferencedAssemblies.AddRange(refs)
params.GenerateExecutable = True
params.OutputAssembly = WhereToSave
provider = New Microsoft.VisualBasic.VBCodeProvider
results = provider.CompileAssemblyFromSource(params, VBSourceCode)
Return True
Catch ex As Exception
MessageBox.Show(ex.ToString)
Return False
End Try
End Function
好的,现在代码可以将VB.NET源代码编译成VB.NET控制台应用程序,谢谢!但是我们如何检查这个results变量是否有错误,我的意思是这一行:results = provider.CompileAssemblyFromSource(params, VBSourceCode)
【问题讨论】:
-
"Sub Main()" & "Dim UserInfo As String = ""Name: User1"""在一行上同时运行这两个语句,因此出现有关“预期语句结束”的错误。此外,如果您想避免“过时”消息 - 消息的其余部分告诉您如何避免它。