Writing Binary Data in WSH - Fixing the file contents
(Page 3 of 4 )
All is well and good. The stream can be saved to a file and then closed. However, if you try to open the newly-created zip file, Windows will politely inform you that the file is corrupt. When you examine the newly-created file in your trusty hex editor, you will soon see why. The ADO Stream object inserts two unwanted characters at the beginning of the file before we begin writing our characters. That’s no good! Since the ADO Stream object is the only thing we have available capable of reading binary input, we have to go back to it to fix the problem.
.Open
.Type = adTypeBinary
.LoadFromFile strPath
This time we open a new stream but we open it in binary mode. Reading a stream in binary mode will read the file contents into a true binary array. We don’t have any way of manipulating a binary array, but that’s okay. At least we have the binary data to work with. The ADO Stream now contains the binary contents of our zip file.
.Position = 2
arrBytes = .Read
.Position = 0
.SetEOS
.Write arrBytes
.SaveToFile strPath, adSaveCreateOverwrite
.Close
End With
This piece of code is where the magic happens. The stream object is kind of similar to a recordset. We can read it one character at a type from beginning to end, and a marker keeps track of where we are. So by manually setting that marker position to 2, we can avoid reading the two unwanted characters at the beginning of our binary stream.
Once the binary data has been read, we can set the cursor position back to 0, or the beginning of the stream. The SetEOS method is then used to set the End Of Stream marker to the current cursor position. This effectively empties the contents of the stream object. Now we can write the cleaned-up binary back to the file.
Next: Writing binary files with FSO >>
More Code Examples Articles
More By Nilpo