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

前端之家收集整理的这篇文章主要介绍了VB.NET动态执行代码生成可执行文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

格式如下:

PathName生成的可执行文件路径

Comment:执行的代码内容

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

Private Function Test(ByVal PathName As 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.HasErrors Then

Comment = ""

For Each Item As System.CodeDom.Compiler.CompilerError In 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

原文链接:https://www.f2er.com/vb/259322.html

猜你在找的VB相关文章