Search And Replace within A Binary Stream

2.8k views Asked by At

I am trying to change a value in a bytestream array. I am looking for the Null value, and I want to change it to a space. When I try to access the array I get an error message "Type Mismatch".

My VBS Code:

Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2
Const adSaveCreateNotExist=1
'Create Stream object
Dim BinaryStream
Set BinaryStream = CreateObject("ADODB.Stream")
Dim InputFile
InputFile="C:\Users\oferbe\Documents\Tfachut\prepr\Testinput.txt"

'Specify stream type - we want To get binary data.
BinaryStream.Type = adTypeBinary

'Open the stream
BinaryStream.Open
'Load the file data from disk To stream object
BinaryStream.LoadFromFile InputFile

'Open the stream And get binary data from the object
ReadBinaryFile = BinaryStream.Read
BinaryStream.Close

For i = 0 to UBound(ReadBinaryFile)
  If ReadBinaryFile(i)=00 Then ReadBinaryFile(i)=20
Next

BinaryStream.Open
'BinaryStream.Write ByteArray
BinaryStream.Write ReadBinaryFile
Dim OutPutFile
OutPutFile="C:\Users\oferbe\Documents\Tfachut\prepr\Ofer"
'Save binary data To disk
BinaryStream.SaveToFile OutPutFile, adSaveCreateOverWrite
1

There are 1 answers

0
Ansgar Wiechers On

The Read operation returns a byte array, which is basically a binary string having some of the properties of a VBScript array, but not all of them. You're better off reading the binary stream as a regular string:

inputFile  = "C:\path\to\your\input.bin"
outputFile = "C:\path\to\your\output.bin"

Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2
stream.Charset = "Windows-1252"
stream.LoadFromFile inputFile
data = stream.ReadText
stream.Close

data = Replace(data, Chr(0), Chr(32))

stream.Open
stream.Type = 2
stream.Charset = "Windows-1252"
stream.WriteText data
stream.SaveToFile outputFile, 2
stream.Close

Set stream = Nothing