Wine Too
Wine Too

Reputation: 4655

Writing binary files without header

I often uses binary files for storing data which is readable through many programming languages. Also in VB.Net. When VB6 create binary file it contains only binary data but when VB.NET creates it like in this example:

    Dim fs As New FileStream(setup_file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
    Dim bf As New BinaryFormatter()
    bf.Serialize(fs, myStruct)
    fs.Close()

... before data, system creates some header with data description. That can make problems on reading such files in different programming languages and/or different OS-es, mostly in finding header length.

I can make same files at "oldfashion" way and those don't contain any "header", just pure data but VB.NET programmers often say that they strongly recommend new style.
This is "oldfashion" VB6 like way:

    Dim fnum = FreeFile()
    FileOpen(fnum, setup_file, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.Shared, Len(myStruct))
    FilePut(fnum, myStruct, 1)
    FileClose(fnum)

Question is:

Can I create/write binary files with FileStream, BinaryFormatter and Serialization but avoid creation of header in file with data and how to do this?

Upvotes: 0

Views: 969

Answers (2)

prprcupofcoffee
prprcupofcoffee

Reputation: 2970

A .NET deserializer is responsible for instantiating the objects it is deserializing, so it needs to know the type of the data it's reading, and that is why the serializers put it there. If you don't want that, you have to write your own code.

What VB.NET programmers often say they recommend is good input, but only if you control both sides - the reader and the writer. If the reader reading the data you write has constraints (e.g., Objective C code running on a Mac), then you decide what goes into that file.

Take a look at System.IO.BinaryWriter and System.IO.BinaryReader. They allow you to write binary files with no "headers" other than what you decide to put there. It's still possible to have issues with byte order and things like that, but binary serialization wouldn't have helped with that anyway.

Upvotes: 2

Jim O'Neil
Jim O'Neil

Reputation: 23774

Serializing the object means it's adding some additional information beyond the raw data so that it can be deserialized later into the same object class. It's not what you want if you're planning to read data on other platforms.

BinaryWriter will get you there, but not in one convenient call like FilePut.

Upvotes: 1

Related Questions