VB.NET动态执行代码生成可执行文件

来源:互联网 发布:智能风水罗盘软件 编辑:程序博客网 时间:2024/04/30 00:20

格式如下:

PathName:生成的可执行文件路径

Comment:执行的代码内容

函数成功返回:Success.失败返回Failed或者编译出错的代码

Private Function Test(ByVal PathNameAs String, ByVal Comment As String) As String

        Try

            Dim comp As VBCodeProvider = New VBCodeProvider

            Dim parms As System.CodeDom.Compiler.CompilerParameters =New System.CodeDom.Compiler.CompilerParameters

            parms.GenerateExecutable = True

            parms.OutputAssembly = PathName

            parms.TreatWarningsAsErrors = False

            parms.ReferencedAssemblies.Add("System.Windows.Forms.dll")

            Dim code As System.Text.StringBuilder = New System.Text.StringBuilder

            code.Append(Comment)

            Dim res As System.CodeDom.Compiler.CompilerResults = comp.CompileAssemblyFromSource(parms, code.ToString)

            If res.Errors.HasErrorsThen

                Comment = ""

                For Each Item As System.CodeDom.Compiler.CompilerErrorIn res.Errors

                    Comment += Item.ErrorText + vbCrLf

                Next

                Return Comment

            Else

                Return "Success!"

            End If

        Catch ex As Exception

            Return "Failed!"

        End Try

End Function

 

例子:

comment=

Imports System.Windows.Forms
Imports System
Module Test
Sub Main()
Dim i As Integer=0
Dim sum As Integer=0
For i=0 To 100 Step 1
sum+=i
Next
Console.WriteLine(sum)
Console.ReadLine()
End Sub
End Module

PathName=“C:\test.exe”

执行上面的Test(PathName,Comment)后在C盘生成一个test.exe程序,运行这程序界面显示5050

原创粉丝点击