How to compile a VB.NET console application's source code using VB.NET
I need to create a VB.NET function that takes the source code of a VB.NET console application and compile it into a console application.
For example, this is the VB.NET source code for the console application:
Module Module1
Sub Main()
Dim UserInfo As String = "Name: User1"
System.Console.WriteLine(UserInfo)
System.Console.ReadLine()
End Sub
End Module
My code so far:
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: Here is the solution:-
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
Ok, now the code can compile VB.NET source code into VB.NET console application, thanks ! But how do we check if there is any error in this results
variable, I mean this line: results = provider.CompileAssemblyFromSource(params, VBSourceCode)
The "Obsolete" warning message tells you how to avoid receiving it - use the method defined on the CodeProvider class directly, e.g.
provider = New Microsoft.VisualBasic.VBCodeProvider
'compiler = provider.CreateCompiler
results = provider.CompileAssemblyFromSource(params, VBSourceCode)
精彩评论