Compressed Folders in WSH - Getting a Byte Array in VBScript
(Page 3 of 4 )
We know at this point that we need a byte array to write a binary stream to a file. VBScript doesn’t provide a method of creating one, but we can read a byte array from a dummy file that we create with the information that we would like in it.
objStream.Open
objStream.Type = adTypeBinary
objStream.LoadFromFile strPath
We need to reopen the Stream object by using its Open method again. This time we’ll set its Type to binary so that it reads in a binary byte array. Finally, we can use the LoadFromFile method to load the contents of our dummy file into the data stream.
objStream.Position = 2
arrBytes = objStream.Read
Remember that we want to skip the first two unwanted bytes of information. To do this we’ll use the Stream object’s Position property to set the cursor position to the third character. Positions are zero-based so we’ll set the property value to 2. The Read method is then used to return a byte array from the stream.
objStream.Position = 0
objStream.SetEOS
objStream.Write arrBytes
Now we need to write our byte array back to the file in binary form. We can reuse the binary stream that we already have open by setting the cursor position back to the beginning and using the SetEOS method. This method sets the End Of Stream marker to the current cursor position. By setting it to the beginning of the stream, we can effectively dump the existing stream data.
objStream.SaveToFile strPath, adSaveCreateOverwrite
objStream.Close
Set objStream = Nothing
Now you can use the SaveToFile method to write the stream to file in true binary fashion. Notice that we’re now overwriting the dummy file. We’re all finished, so you can close the stream and disconnect its object.
Voila! A series of workarounds has enabled us to create a true byte array and write a binary file in VBScript using only native objects. A quick peek with the hex editor shows that our zip file is exactly like the original one that we inspected when we began.
Next: Adding and Extracting files >>
More Windows Scripting Articles
More By Nilpo