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)
"Sub Main()" & "Dim UserInfo As String = ""Name: User1"""runs those two statements together on a single line, hence the error about "end of statement expected". Also, if you want to avoid the "obsolete" message - the rest of the message tells you how to avoid it.