vbscript to create a binary file
-
Wednesday, December 12, 2012 5:53 AM
Hi Experts!
I'm back; and need your help in creating a binary file using vbscript. I heard somewhere it is not possible, so thought what better place to ask this than here.
FYI, I'm able to read and write binary file using adodb.stream
TIA
- thestriver
- Changed Type Bill_StewartMicrosoft Community Contributor, Moderator Wednesday, December 12, 2012 12:53 PM User asked a question
All Replies
-
Wednesday, December 12, 2012 6:05 AM
I just checked to see if the below code for read binary file works on an actual binary file- it shows junk values as output:
path = "C:\Projects\Ocho\Bala\binary\default1.bin"
readBinary(path)
Function readBinary(path)
Dim a
Dim fso
Dim file
Dim i
Dim ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.getFile(path)
If isNull(file) Then
MsgBox("File not found: " & path)
Exit Function
End If
Set ts = file.OpenAsTextStream()
a = makeArray(file.size)
i = 0
While Not ts.atEndOfStream
a(i) = ts.read(1)
i = i + 1
Wend
ts.close
readBinary = Join(a,"")
wscript.echo readBinary
End Function
Function makeArray(n)
' Small utility function
Dim s
s = Space(n)
makeArray = Split(s," ")
End FunctionThe reason I'm looking to create, read and write into binary file is I have an application that stores temporary data in the working directory. And this data is secure data and should not be opened and seen by everybody. So looking to store this data in binary file. I'm okay if there are other alternatives to this idea
TIA
- thestriver
-
Wednesday, December 12, 2012 6:48 AM
Although the File System Object is not designed to handle binary files, you can still trick it into doing so. The code below will do this:
- Read a binary file into a string.
- Replace the first ten characters with $00 .. $09.
- Write the data into a new binary file.
You can use fc.exe /b to verify the process.
Set oFSO = CreateObject("Scripting.FileSystemObject")
sInput = "d:\tools\beep.exe"
sOutput = "d:\Test.exe"
iSize = oFSO.GetFile(sInput).Size
Set oFile = oFSO.OpenTextFile(sInput)
sData = oFile.Read(iSize)
oFile.Close
sString = ""
For i = 1 To 10
sString = sString & Chr(i)
Next
Set oFile = oFSO.CreateTextFile(sOutput, True)
oFile.Write sString & Mid(sData, 11)
oFile.Close- Marked As Answer by thestriver Tuesday, December 18, 2012 2:44 AM

