Eric's Webspace
Read Binary Data in Scripting

People who use Windows Scripting or who build ASP web pages have no method to read binary data. Microsoft has provided Visual Basic code to create an object to remedy this ( ). As is typical, they don't provide a compiled binary. Just to be nice, I've compiled it as an OCX (instead of as a DLL) with the FREE Visual Basic Control Creation Edition. Compiling as a DLL would have meant using the non-free version of Visual Basic. What good is open source without open compilers?:


The OCX has a "q193998.BinRead" object which exposes a single function "ReadBinFile".  The function return a Byte Array which can be read from scripting. The control needs to be registered before you can use it with a command like:
regsvr32.exe "C:\Wherever\q193998.ocx"

To run the OCX, you'll need to have the Visual Basic 5 run-time files on your computer. You probably already have these files. If not, you can get the runtime files from either of these places:
Ziff-Davis HTTP  Microsoft FTP

Good News:   If you have Microsoft Data Access Components installed, you can read binary files into byte arrays with no special controls needed. Try script like this:

Function ReadByteArray(strFileName)
Const adTypeBinary = 1
Dim bin
Set bin = CreateObject("ADODB.Stream")
bin.Type = adTypeBinary
bin.LoadFromFile strFileName
ReadByteArray = bin.Read
End Function

In the event you need to convert the byte array data into a string, here are three ways to do it:

Function ByteArray2Text(varByteArray)
'Convert byte array into a string with ADODB.Recordset
Dim rs
Const adLongVarChar = 201
Set rs = CreateObject("ADODB.Recordset")
rs.Fields.Append "temp", adLongVarChar, LenB(varByteArray)
rs("temp").AppendChunk varByteArray
ByteArray2Text = rs("temp")
Set rs = Nothing
End Function

Function ByteArray2Text(varByteArray)
'Convert byte array into a string with ADODB.Stream
'Data should be real plain text because binary data will be mangled
Dim byt
Const adTypeText = 2
Const adTypeBinary = 1
Set byt = CreateObject("ADODB.Stream")
byt.Type = adTypeBinary
byt.Write varByteArray
byt.Position = 0
byt.Type = adTypeText
byt.CharSet = "us-ascii"
ByteArray2Text = byt.ReadText
Set byt = Nothing
End Function

Function ByteArray2Text(varByteArray)
'Convert byte array into a string with VBScript
'60kb = 2 seconds, 100kb = 5 seconds, 200kb = 25 seconds
Dim strBuffer, lngCounter
 strData = ""
strBuffer = ""
For lngCounter = 0 to UBound(varByteArray)
strBuffer = strBuffer & Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1)))
'Keep strBuffer at 1k bytes maximum
If lngCounter Mod 1000 = 0 Then
strData = strData & strBuffer
strBuffer = ""
End If
ByteArray2Text = strData & strBuffer
End Function


Lost? Look at the site map.

Bad links? Questions? Send me mail.

Ask Jeeves