# VB Binary Read/Write



## BuntyKainth (Aug 10, 2003)

Hi i was wondering if there is a way in which i can write some data using vb into a file but in binary format so that if someone opens it it cannot be read. for example a file called 
"C:\windows\desktop\bin.dat" cantains that data "HEllo" but in binary.

also having done this is there a way in which i can then open the binary file and read the data and convert it back into text to display within a text field. 

ive tryed doing it but something seems to go wrong. i would really appreciate some help on this guys its kinda difficult.

Thankyou have a nice day.


----------



## TimCottee (Oct 10, 2001)

A simple way of doing this is as follows, all this essentially does is do a replace of characters with others so that it appears to scramble the content. There is no real encryption and it could be decoded if someone wanted to spend the time:


```
Private Sub Command1_Click()
    WriteFile "c:\development\test.txt", "Hello there how is this then?"
End Sub

Private Sub Command2_Click()
    MsgBox ReadFile("c:\development\test.txt")
End Sub

Private Sub WriteFile(ByVal FileName As String, ByVal Content As String)
    Open FileName For Binary As #1
    Put #1, , Encode(Content)
    Close #1
End Sub

Private Function ReadFile(ByVal FileName As String) As String
    Open FileName For Input As #1
    ReadFile = Decode(Input(LOF(1), 1))
    Close #1
End Function

Private Function Encode(ByVal Content As String) As String
    Dim aryBytes() As String
    ReDim aryBytes(Len(Content))
    Dim intPos As Integer
    For intPos = 1 To Len(Content)
        intChar = Asc(Mid(Content, intPos, 1)) - 64
        If intChar < 0 Then intChar = intChar + 256
        aryBytes(intPos) = Chr(intChar)
    Next
    Encode = Join(aryBytes, "")
End Function

Private Function Decode(ByVal Content As String) As String
    Dim aryChars() As String
    ReDim aryChars(Len(Content))
    Dim intPos As Integer
    For intPos = 1 To Len(Content)
        intChar = Asc(Mid(Content, intPos, 1)) + 64
        If intChar > 255 Then intChar = intChar - 256
        aryChars(intPos) = Chr(intChar)
    Next
    Decode = Join(aryChars, "")
End Function
```


----------



## BuntyKainth (Aug 10, 2003)

Wicked dood thats brillient, nice one have a nice day


----------

