Read binary file as string

YasserKhalil
PlatinumLounger
Posts: 4913
Joined: 31 Aug 2016, 09:02

Read binary file as string

Post by YasserKhalil »

Hello everyone

In the following code, I convert a string and write it to a binary file

Code: Select all

Sub Write_Binary_File()
    Dim sFilename As String, s As String, i As Integer, nFileNum As Integer

    s = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
    sFilename = ThisWorkbook.Path & "\Temp.dat"
    
    nFileNum = FreeFile
    Open sFilename For Binary Lock Read Write As #nFileNum
    
    For i = 0 To Len(s)
        Put #nFileNum, , Mid(s, i + 1, 1)
    Next i

    Close #nFileNum
End Sub
Now how can I convert the binary file to a string that is stored in the s variable?

User avatar
HansV
Administrator
Posts: 78483
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Read binary file as string

Post by HansV »

Code: Select all

Sub Read_Binary_File()
    Dim sFilename As String, s As String, nFileNum As Integer
    sFilename = ThisWorkbook.Path & "\Temp.dat"
    nFileNum = FreeFile
    Open sFilename For Binary Access Read As #nFileNum
    ReDim A(1 To LOF(nFileNum))
    Get nFileNum, , A
    Close #nFileNum
    s = Join(A, "")
    MsgBox s
End Sub
Best wishes,
Hans

YasserKhalil
PlatinumLounger
Posts: 4913
Joined: 31 Aug 2016, 09:02

Re: Read binary file as string

Post by YasserKhalil »

Thank you very much for the great solution.