Search code examples
vbscriptasp-classicbinary

How can I write binary data to disk in VBScript?


I have a binary string that I need to write to a file. I have a feeling that this should be a simple procedure, but then again, VBScript. The FileSystemObject is of no help, since it munges the data. The Stream object looks promising, with it's adBinaryMode and its Write method, but the Write method requires a byte array and won't seem to accept a variant array instead. Since VBScript arrays are all variant arrays, this seems problematic.

So, how do I just write the data to a file?

EDIT: I should add that the whole thing has to be VBScript. No extra components. Sorry, I don't like it either.


Solution

  • It's also possible with the ordinary FileSystemObject, here is code I'm using in custom upload script that I wrote long time ago using code I found online that converts binary string to ASCII:

    Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.CreateTextFile("file path here")
    objFile.Write(RSBinaryToString(strBinaryContents))
    objFile.Close
    Set objFile=Nothing
    Set objFSO=Nothing
    
    Private Function RSBinaryToString(xBinary)
        'Antonin Foller, http://www.motobit.com
        'RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
        'to a string (BSTR) using ADO recordset
    
        Dim Binary
        'MultiByte data must be converted To VT_UI1 | VT_ARRAY first.
        If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary
    
        Dim RS, LBinary
        Const adLongVarChar = 201
        Set RS = CreateObject("ADODB.Recordset")
        LBinary = LenB(Binary)
    
        If LBinary>0 Then
            RS.Fields.Append "mBinary", adLongVarChar, LBinary
            RS.Open
            RS.AddNew
            RS("mBinary").AppendChunk Binary 
            RS.Update
            RSBinaryToString = RS("mBinary")
        Else  
            RSBinaryToString = ""
        End If
    End Function
    
    Function MultiByteToBinary(MultiByte)
        '© 2000 Antonin Foller, http://www.motobit.com
        ' MultiByteToBinary converts multibyte string To real binary data (VT_UI1 | VT_ARRAY)
        ' Using recordset
        Dim RS, LMultiByte, Binary
        Const adLongVarBinary = 205
        Set RS = CreateObject("ADODB.Recordset")
        LMultiByte = LenB(MultiByte)
        If LMultiByte>0 Then
            RS.Fields.Append "mBinary", adLongVarBinary, LMultiByte
            RS.Open
            RS.AddNew
            RS("mBinary").AppendChunk MultiByte & ChrB(0)
            RS.Update
            Binary = RS("mBinary").GetChunk(LMultiByte)
        End If
        MultiByteToBinary = Binary
    End Function