编译VB.NET控制台应用程序的源代码,我需要创建一个VB.NET函数,它接受一个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
UPDATE:这里是解决方案: -
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)
'“子的Main()”&“昏暗的UserInfo作为字符串=‘’姓名:用户1”,“”'运行这两个语句一起在一行上,因此,有关错误的“预期语句的末尾”。另外,如果你想避免“过时”的消息 - 消息的其余部分*告诉你如何避免它。 –