WScript in VB.NET?
Asked Answered
M

1

7

This is a snipet of code from my program:

WSHShell = WScript.CreateObject("WScript.Shell")

But for some reason, "WScript" is not declared. I know that this code works in VBScript but i'm trying to get it to work with vb.net. Whats going wrong?

Mindszenty answered 6/3, 2012 at 19:7 Comment(4)
Check Eric Lippert's Blog blogs.msdn.com/b/ericlippert/archive/2003/10/08/53175.aspxNorri
@Norri thats an interesting post but i still would like to know how to adapt my code to vb.netMindszenty
you can run script as separate processNorri
As I mention on Eric Lippert's blog, there is no need for WScript within .Net. You should be rewriting the code to use native classes.Seamus
Q
12

The WScript object is specific to Windows Script Host and doesn't exist in .NET Framework.

Actually, all of the WScript.Shell object functionality is available in .NET Framework classes. So if you're porting VBScript code to VB.NET, you should rewrite it using .NET classes rather than using Windows Script Host COM objects.


If, for some reason, you prefer to use COM objects anyway, you need to add the appropriate COM library references to your project in order to have these objects available to your application. In case of WScript.Shell, it's %WinDir%\System32\wshom.ocx (or %WinDir%\SysWOW64\wshom.ocx on 64-bit Windows). Then you can write code like this:

Imports IWshRuntimeLibrary
....
Dim shell As WshShell = New WshShell
MsgBox(shell.ExpandEnvironmentStrings("%windir%"))


Alternatively, you can create instances of COM objects using

Activator.CreateInstance(Type.GetTypeFromProgID(ProgID))

and then work with them using late binding. Like this, for example*:

Imports System.Reflection
Imports System.Runtime.InteropServices
...

Dim shell As Object = Nothing

Dim wshtype As Type = Type.GetTypeFromProgID("WScript.Shell")
If Not wshtype Is Nothing Then
    shell = Activator.CreateInstance(wshtype)
End If

If Not shell Is Nothing Then
    Dim str As String = CStr(wshtype.InvokeMember(
        "ExpandEnvironmentStrings",
        BindingFlags.InvokeMethod,
        Nothing,
        shell,
        {"%windir%"}
    ))
    MsgBox(str)

    ' Do something else

    Marshal.ReleaseComObject(shell)
End If

* I don't know VB.NET well, so this code may be ugly; feel free to improve.

Quantifier answered 7/3, 2012 at 7:36 Comment(1)
+1, but the recommendation you make at the bottom should probably be at made at the top, where it can't be missed!Vadim

© 2022 - 2024 — McMap. All rights reserved.