Binary File, Array Scripting Secrets - Writing Binary Files with the FileSystemObject
(Page 2 of 4 )
Writing Binary Files – Method 2 (FileSystemObject)
I used the ADODB.Stream method of creating binary files for quite a while before stumbling onto this next solution. The idea was originally published by Eric Phelps, but unfortunately I don’t have a link to that.
While the ADODB method is effective, it does have one major drawback. Each file has to be written to disk twice. While this is a fairly quick process, just knowing that it was happening made the method seem inefficient to me. This method doesn’t post that problem.
strPath = "C:Zip.zip"
Const ForWriting = 2
Set objFso = CreateObject("Scripting.FileSystemObject")
With objFso.OpenTextFile(strPath, 2, True)
For x = 1 To 44 Step 2
.Write Chr(Clng("&h" & Mid("504B0506000000000000000000000000000000000000",x,2)))
Next
.Close
End With
This method exploits the FileSystemObject’s ability to create an empty file on disk. The OpenTextFile method has an optional third parameter that, when set to true, will create a new file on disk if the specified file doesn’t already exist. This file is created without any contents. It’s just an empty shell. Writing binary data directly to that file would accomplish the task at hand.
The method uses an interesting manner to write the binary data. A string of byte characters is read in a For loop, two characters at a time. A “&h” is then added to the beginning of the two-character string. You may recognize this as VBS’s way of explicitly writing hexadecimal values.
The string containing the hex value is then converted to a decimal number with the Clng function. Once you have a decimal representation of the binary character, it can be written directly to the file with the Chr function.
Next: Removing an array element >>
More Code Examples Articles
More By Nilpo