• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 483
  • Last Modified:

How to use a binary file in C# that was created in C++ or Delphi ?

Say I have a simple Delphi structure:

TestType = record
    first_name: array [0 .. 30] of Char;
    last_name: array [0 .. 30] of Char;

Same strucure in C++:

struct TestType
    char first_name[31];
    char last_name[31];

Now then, I instantiated an object of that structure and saved it to a file, called "test.bin". I need to be able to read that file in C# 2.0. So I created the following C# structure:

struct TestType
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 31)]    
    public string first_name;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 31)]    
    public string last_name;

Now, to read the file, I do the following:

FileStream testFile = null;
    BinaryFormatter binFormat = new BinaryFormatter();

    testFile = new FileStream("test.bin", FileMode.Open, FileAccess.Read);

    TestType testType = (TestType)binFormat.Deserialize(testFile);
    if (testFile != null)

When I do that, I get the following exception

"Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization."

Please help.
1 Solution
The Object serializer is for .NET serialised objects.  I think you just want to do a binary read of the strings from the file and put them in the object yourself.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now