Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Read/Write Structures to binary file

Status
Not open for further replies.

TLN1

Programmer
Jan 5, 2003
11
US
I always used Put and Get in previous versions of VB6 to easily write the contents of a structure to a binary file - it was one line of code. The new VB.NET FileGet/FilePut functions are terribly slow when compared to BinaryReader/writer classes so by reading a couple of books I found a way to read and write structures using BinaryReader/writer that did give me increased performance but still not as fast as native VB6 Get/Put functions. There are however certain complexities when using BinaryReader/writer, first of which is I must Read/Write individual elements of the structure as in:

Try
tPntx.ipt = bcRead.ReadInt32()
tPntx.bid = bcRead.ReadBytes(4)
tPntx.anpt = bcRead.ReadString
tPntx.desc = bcRead.ReadString
tPntx.no = bcRead.ReadDouble()
tPntx.ea = bcRead.ReadDouble()
tPntx.el = bcRead.ReadDouble()
Catch Errx As Exception
End Try

The other complexity is writing strings - they must be preinitialized to the desired len using an Initialize sub of the structure. If I try to find the len of the tPntx structure, the len returned is two short because the strings are preceded (when written to disc) by a byte len char (which adds two bytes to the byte len on disc). I found this out by disassembling the file byte by byte. So for each string you have, you must add the byte len char for EACH string to get the correct len of this structure in bytes on disc. This byte char in decimal is the length of the current string element. This next discovery really confused me - the string is NOT written to disc as a Unicode string - it is written as an ANSI string ie each char takes up only one byte on disc not 2 as I expected - why?

So is there an easier way to write structures to disc than how I am doing it? Should I just write an array of char bytes instead of a string ie use .ReadBytes(?) because the string is written to disc as an ANSI char? I must stick to this paradigm and can not redesign the entire file IO system because other (some legacy) applications access this binary file at the same time the parent application has it open.

Guidance from a knowledgeable person would be appreciated.

Thanks,
Terry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top