Read / Write hex values in file

DelScript

New member
Joined
Mar 2, 2009
Messages
3
Programming Experience
Beginner
Hi Guys

I'm new to VB.net and have only a few projects under my belt.

This one has me stumped!!

I need to open a file and search its contents hex byte by byte. (Similar to Hex editor). On finding a particular value I need to replace it with a set hex value then write and close the file.

So far I have only managed to read / write the ascii equivilant.

I would appreciate pointers towards a solution.

Many Thanks
 
Use a FileStream to read/write bytes, you can also use a BinaryReader/Writer for that stream to read/write other data types easier. If you need to go from byte or other data types values to hex strings use the ToString method where you specify "X"/"X2" hex format.
 
So far I have only managed to read / write the ascii equivilant.

Er. There is no difference. When you say "Hex" you mean a representation of the bytes in the file, which the ascii also is. The only difference being that some bytes have no meaning in ascii and are lost

Here is the code you would use to scan an entire file and change every occurrence of byte 7A (z in ascii, but that is immaterial) to be 69 (i in ascii, again, immaterial)

I picked on bytes in the ascii charset because you can see the effect on a text file, but if you have a hex editor you'll see the changes regardles sof what bytes are involved.

Jsut remember, that "hex" is a display notion, not a way of storing data, and that all files (ascii text, binary, whatever) are just a collection of bytes. THis method reads and writes bytes:

VB.NET:
Dim fs As New FileStream("c:\temp\tmp", FileMode.Open, FileAccess.ReadWrite) 
Dim b As Integer = fs.ReadByte() 
While b <> -1 
    If b = &H7a Then 
        fs.Seek(-1, SeekOrigin.Current) 
        fs.WriteByte(&H69) 
    End If 
    b = fs.ReadByte() 
End While 
fs.Close() 
fs.Dispose()

REmember to dispose your filestream when youre done with it
 
Back
Top