Is it possible to get an instance of a .Net string object in VBScript?

In VBScript, you can use certain .net classes using COM automation. This is useful if you want to use dynamic arrays, lists, queues, etc.

It would be nice if I could use strings as objects, so I could do all the fancy string things , but whenever I pass a string from another object, this is seen as VBScript as a literal string, and not as a string object:

Set s = CreateObject("System.Text.StringBuilder") s.Append_3 "I love deadlines. I like the whooshing sound they make as they fly by." ' This gives me the literal string MsgBox s.ToString text = s.ToString ' But unfortunately this won't work MsgBox s.ToString.Length Set stringRef = s.ToString 

Also, creating a string as a COM object will not work:

 Set s = CreateObject("System.String") ' Nope. 

Is there anyone who has dealt with this, or are there other thoughts about this?

+7
source share
2 answers

You can use some methods and properties, but not all of them. The following works, but since using toString you have a vbscript variable that behaves as such.

 Set s = CreateObject("System.Text.StringBuilder") s.Append_3 "I love deadlines. I like the whooshing sound they make as they fly by." s.Append_3 "and the rest." wscript.echo s.Length wscript.echo s.Capacity wscript.echo chr(s.chars(0)) wscript.echo s.Replace("t", "d").Replace("l", "k").toString 

gives

 83 140 I I kove deadkines. I kike dhe whooshing sound dhey make as dhey fky by.and dhe resd. 

But, for example, the following does not work, although this is the stringbuilder method http://msdn.microsoft.com/en-us/library/system.text.stringbuilder_methods.aspx do not ask me why

 s.Insert 1, "insert this" 

and

 s.Insert_2 7, "insert this" 

working

I also program in Ruby, where you can also use these objects, and there it is the same behavior. For some objects, I can list properties or methods, for example, for Excel

 require 'win32ole' excel = WIN32OLE.new('Excel.Application') properties = excel.ole_get_methods properties.each do |property| p property.to_s end 

gives a very long list, for example

 "Application" "Creator" "Parent" "ActiveCell" "ActiveChart" "ActiveDialog" "ActiveMenuBar" "ActivePrinter" "ActiveSheet" "ActiveWindow" "ActiveWorkbook" etc etc 

But not so for System.Text.Stringbuilder, I suppose this is due to the way the programmer exposes his methods and properties from the outside.

Unfortunately, I do not think that you can directly use System.String in vbscript.

+7
source

You tried. Msgbox len (s.ToString) or just MsgBox (s.Length)

Alternatively, you can create your own .Net class and expose it to com, which will act as a wrapper for the static string functions you want to open ...

0
source

All Articles