VB.NET中的WScript?

use*_*604 7 vb.net vbscript wsh

这是我程序中的代码片段:

WSHShell = WScript.CreateObject("WScript.Shell")
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,未声明"WScript".我知道这段代码在VBScript中有效但我正试图让它与vb.net一起工作.什么出错了?

Hel*_*len 11

WScript对象特定于Windows脚本宿主,在.NET Framework中不存在.

实际上,WScript.Shell.NET Framework类中提供了所有对象功能.因此,如果您将VBScript代码移植到VB.NET,则应使用.NET类重写它,而不是使用Windows Script Host COM对象.


如果出于某种原因,您仍然希望使用COM对象,则需要向项目添加适当的COM库引用,以使这些对象可用于您的应用程序.如果是WScript.Shell,它是%WinDir%\ System32\wshom.ocx(或64位Windows上的%WinDir%\ SysWOW64\wshom.ocx).然后你可以写这样的代码:

Imports IWshRuntimeLibrary
....
Dim shell As WshShell = New WshShell
MsgBox(shell.ExpandEnvironmentStrings("%windir%"))
Run Code Online (Sandbox Code Playgroud)


或者,您可以使用创建COM对象的实例

Activator.CreateInstance(Type.GetTypeFromProgID(ProgID))
Run Code Online (Sandbox Code Playgroud)

然后使用后期绑定与他们合作.像这样,例如*:

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
Run Code Online (Sandbox Code Playgroud)

*我不太了解VB.NET,所以这段代码可能很难看; 随意改进.

  • +1,但您在底部的建议可能应该在顶部进行,不容错过! (2认同)