Writing Binary Data in WSH
(Page 1 of 4 )
It’s been said over and over again that VBScript does not support the creation of binary files. There also aren’t any objects available to WSH that provide that support. In fact, Microsoft will swear that it’s true. If you don’t believe me, just read their documentation. In light of that defining argument, today I’ll be showing you not one, but two ways to do the impossible.
Writing Binary Data to Files
The ability to write binary files directly was never provided in VBScript. The powers that were decided that the functionality wasn’t necessary in Visual Basic’s Scripting Edition and that it would be too complicated to code it in, so it never was. I stumbled upon a workaround quite some time ago; you may have seen it in action in my article Compressed Folders in WSH.
The concept is quite simple. I learned to exploit the ADODB.Stream object that is used for creating Stream objects. The ADODB.Stream can create both text streams and binary streams. This worked out pretty conveniently, but it did require a bit of a workaround, as you’ll see soon. VBScript doesn’t have built-in binary processing support, so it does not provide a way to create a true byte array. But enough about that for now, let’s take a look at the code.
strPath = "C:Zip.zip"
Const adTypeBinary = 1
Const adTypeText = 2
Const adWriteChar = 0
Const adSaveCreateNotExist = 1
Const adSaveCreateOverwrite = 2
With CreateObject("ADODB.Stream")
.Open
.Type = adTypeText
.WriteText ChrB(&h50) & ChrB(&h4B) & ChrB(&h5) & ChrB(&h6)
For i = 1 To 18
.WriteText ChrB(&h0)
Next
.SaveToFile strPath, adSaveCreateNotExist
.Close
.Open
.Type = adTypeBinary
.LoadFromFile strPath
.Position = 2
arrBytes = .Read
.Position = 0
.SetEOS
.Write arrBytes
.SaveToFile strPath, adSaveCreateOverwrite
.Close
End With
This code sample will write binary data directly to a file. The result is a Compressed Folder.
Next: ADODB.Stream for writing binary files >>
More Code Examples Articles
More By Nilpo