Friday, October 19, 2007

Running VB.NET code in VBScript or other apps

Here is how you can write a .NET component and use it in a script. First, create a library that contains the code you want to run.

Public Class FileWriter
Public Sub Save(ByVal PathAndFileName As String)
Try
Dim FileStream As New System.IO.StreamWriter(PathAndFileName, False)
FileStream.WriteLine("Hello World")
FileStream.Flush()
FileStream.Close()
FileStream.Dispose()

Catch e As Exception
Dim fs As New System.IO.StreamWriter("C:\error.txt", True)
fs.WriteLine("Exception: {1}", 1, e.Message)
fs.Flush()
fs.Close()
fs.Dispose()
Throw e
End Try

End Sub
End Class


Then compile the library and run regasm c:\project\bin\NameOfDLL.dll /CODEBASE to register it. Regasm is in your .net folder. That will register the dll so you can use it later. Regsvr32 is for non .NET dlls. Your script is next. Save it as a .vbs file.

dim fs
set fs = CreateObject("Project1.FileWriter")
fs.save "c:\file.txt"
set fs = nothing

Anyplace you can call CreateObject, you should be able to use your class. VBA in office is one such place. And I did not test this code, I just gutted another project to have some examples.

Related: Running vbs from .net code

No comments:

Post a Comment