WScript in VB.NET?

This is the snippet of code from my program:

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

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

+6
source share
1 answer

The WScript specific to the Windows Script Host and does not exist in the .NET Framework.

In fact, all of the functionality of WScript.Shell available in the .NET Framework classes. Therefore, if you port VBScript code to VB.NET, you must rewrite it using .NET classes, and not using Windows Script Host COM objects.


If for any reason you prefer to use COM objects in any case, you need to add the appropriate COM library links to your project so that these objects are available for your application. In the case of WScript.Shell this is% WinDir% \ System32 \ wshom.ocx (or% WinDir% \ SysWOW64 \ wshom.ocx on 64-bit Windows). Then you can write the code as follows:

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


In addition, you can instantiate COM objects using

 Activator.CreateInstance(Type.GetTypeFromProgID(ProgID)) 

and then work with them using late binding. 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 very well, so this code can be ugly; Feel free to improve.

+10
source

Source: https://habr.com/ru/post/910107/


All Articles