【问题标题】:How to compile a VB.NET console application's source code using VB.NET如何使用 VB.NET 编译 VB.NET 控制台应用程序的源代码
【发布时间】: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""" 在一行上同时运行这两个语句,因此出现有关“预期语句结束”的错误。此外,如果您想避免“过时”消息 - 消息的其余部分告诉您如何避免它。

标签: .net vb.net


【解决方案1】:

“过时”警告消息告诉您如何避免收到它 - 直接使用在 CodeProvider 类上定义的方法,例如

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多