As CompilerResults = provider.CompileAssemblyFromFile(cp, _
sourceName)
If cr.Errors.Count > 0 Then
'' 显示编译错误
Console.WriteLine("编译错误 {0} 编译成 {1}", _
sourceName, cr.PathToAssembly)
Dim ce As CompilerError
For Each ce In cr.Errors
Console.WriteLine(" {0}", ce.ToString())
Console.WriteLine()
Next ce
Else
'' 显示编译成功的消息
Console.WriteLine("原文件 {0} 编译成 {1} 成功完成.", _
sourceName, cr.PathToAssembly)
End If
'' 返回编译结果
If cr.Errors.Count > 0 Then
compileOk = False
Else
compileOk = True
End If
End If
Return compileOk
End Function
2.编译DLL,并动态创建类的实例。(这里类的原文件是Class1.vb文件,放在WebSite的App_Code文件夹中了,实际使用时可以放在任意物理位置。)
Dim strSourceFileName As String = Server.MapPath("~/App_Code/Class1.vb") ''类文件的全路径
Dim strDllPath As String = Server.MapPath("~/App_Code") ''编译后的DLL文件存放的位置
Dim strDllName As String = "" ''DLL的全路径(返回值)
CompileExecutable(strSourceFileName, strDllPath, strDllName) ''编译原文件为DLL文件
Dim a As [Assembly] = [Assembly].LoadFrom(strDllName) ''加载DLL
Dim myType As System.Type = a.GetType("Class1") ''获得Class1的Type
Dim obj As Object = Activator.CreateInstance(myType) ''获得Class1的实例
3.Class1.vb原文件
Public Class Class1Class Class1
Public i As Integer
End Class