2012-03-06 53 views
6

這是代碼從我的程序snipet:VBScript中的WScript?

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

但由於某些原因,「WScript的」不宣。我知道這段代碼在VBScript中工作,但我試圖讓它與vb.net一起工作。發生什麼事了?

+0

檢查Eric Lippert的博客http://blogs.msdn.com/b/ericlippert/archive/2003/10/08/53175.aspx – volody 2012-03-06 19:12:35

+0

@volody這是一個有趣的帖子,但我仍然想知道如何適應我的代碼爲vb.net – user1196604 2012-03-06 19:48:39

+0

您可以將腳本作爲獨立進程運行 – volody 2012-03-06 21:03:04

回答

10

WScript對象特定於Windows腳本宿主,在.NET Framework中不存在。

實際上,所有的WScript.Shell對象功能在.NET Framework類中都可用。因此,如果您將VBScript代碼移植到VB.NET,則應該使用.NET類而不是使用Windows Script Host COM對象來重寫它。


如果由於某種原因,你更喜歡仍要使用COM對象,則需要適當的COM庫引用添加到您的項目,以便有提供給您的應用程序,這些對象。在WScript.Shell的情況下,它是%WinDir%\ System32 \ wshom.ocx(或%WinDir%\ SysWOW64 \ wshom.ocx在64位Windows上)。然後,你可以這樣寫代碼:

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


或者,您可以使用

Activator.CreateInstance(Type.GetTypeFromProgID(ProgID)) 

創建COM對象實例,然後使用後期綁定與他們合作。與此類似,例如*

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 

*我不知道VB.NET好,所以這段代碼可能是醜陋的;隨時提高。

+2

+1,但是您在底部的建議應該是在頂部製作的,不能錯過! – 2012-03-08 08:33:27

+0

@Cody:完成。謝謝! – Helen 2012-03-08 08:49:31