VB.NET动态执行代码生成可执行文件2011-06-16 10:58:32| 分类: VB.net2008或2010 | 标签:动态 执行 代码 |举报 |字号 订阅 格式如下: 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 ” PathName=“C:\test.exe” 执行上面的Test(PathName,Comment)后在C盘生成一个test.exe程序,运行这程序界面显示5050 |
|