Tuesday, September 18, 2007

Convert binary file into bin64 string with VBScript

'
' www.pullnews.com
' Save this code into file ConvertToBin64.vbs
'

If WScript.Arguments.Count= 0 Then
      MsgBox "Usage instruction:" & vbCrLf & _
      "Drag source file and drop on vbs file to process"
      WScript.Quit
End If

Set fso = CreateObject("Scripting.FileSystemObject")
sInFName = WScript.Arguments(0)
sPath = fso.GetParentFolderName (WScript.ScriptFullName)
sOutFName = sPath & "\base64.xml"
SaveToXMLAsBin64 sInFName, sOutFName

' Save binary buffer into xml file in bin64 format
Sub SaveToXMLAsBin64(sInFileName, sOutFileName)
    Set xmlDoc = CreateObject("microsoft.xmldom")
    xmlDoc.async = False
    'create a node
    Set oElement = xmlDoc.createElement("DATA")
    oElement.dataType = "bin.base64"
    oElement.nodeTypedValue = ReadBinaryFile(sInFileName)
    'save file name as well
    oElement.setAttribute "FileName", fso.GetFileName( sInFName )
    xmlDoc.appendChild oElement
    'save file
    xmlDoc.save sOutFileName
End Sub

' Read binary or text file into buffer
Function ReadBinaryFile(FileName)
    Const adTypeBinary = 1
    'Create Stream object
    Dim BinaryStream
    Set BinaryStream = CreateObject("ADODB.Stream")
    '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 FileName
    'Open the stream And get binary data from the object
    ReadBinaryFile = BinaryStream.Read
End Function

No comments: