2011-06-21 57 views
3

編譯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)

+0

'「子的Main()」&「昏暗的UserInfo作爲字符串=‘’姓名:用戶1」,「」'運行這兩個語句一起在一行上,因此,有關錯誤的「預期語句的末尾」。另外,如果你想避免「過時」的消息 - 消息的其餘部分*告訴你如何避免它。 –

回答

2

的「過時」的警告信息告訴您如何避免接受它 - 使用直接在CodeProvider類中定義的方法,例如

provider = New Microsoft.VisualBasic.VBCodeProvider 
'compiler = provider.CreateCompiler 
results = provider.CompileAssemblyFromSource(params, VBSourceCode) 
+0

+1感謝您的幫助! – Predator