user1219310
user1219310

Reputation: 732

Read VB 6 binary file in C#

I have a binary file written by VB6 application and now would like to use C# application to read the VB6 exported binary file. I have used the Microsoft.VisualBasic.dll into my C# project.

However there are some data inconsistency in C# application but I have check it in VB.net and it works nicely as well. (I convert from VB6 to VB.net, then VB.net to C#)

enter image description here

The screenshot represents the result from reading binary file by using C# and VB.Net application. VB.Net is my expected result and now my C# application was showing inconsistency result

Both are double values in C# and VB.NET, and based on my observation, the int, string values looks fine.

In C# I was using statement shown as below, BinaryDetails is struct and inside have few double variables

ValueType DetailsValueType = (ValueType)BinaryDetails;
FileSystem.FileOpen(FileNumber, FileName, OpenMode.Binary, OpenAccess.Read);
FileSystem.FileGet(FileNumber, ref DetailsValueType);

I have change the data type in C# from double to float, still not my expected result: enter image description here

Upvotes: 1

Views: 1040

Answers (1)

Hans Passant
Hans Passant

Reputation: 941218

You can reverse-engineer this kind of mishap with a little test program:

class Program {
    static void Main(string[] args) {
        var value1 = 3.49563395756763E-310;
        var bytes1 = BitConverter.GetBytes(value1);
        Console.WriteLine(BitConverter.ToString(bytes1));
        var value2 = 101.325;
        var bytes2 = BitConverter.GetBytes(value2);
        Console.WriteLine(BitConverter.ToString(bytes2));
    }
}

Output:

CC-CC-CC-54-59-40-00-00
CD-CC-CC-CC-CC-54-59-40

Note how you are definitely on the right track, you are reading correct byte values from the file. Those doubles have CC-54-59-40 in common. It is just that you read the data misaligned. You started reading too late, off by 2 bytes.

That's because your BinaryDetails is not an exact match with the data in the file. Do keep in mind that you have to assume the file contains VB6 data types. They are slightly different from C# types:

  • VB6 file data is tightly packed, you need [StructLayout(LayoutKind.Sequential, Pack = 1)]
  • A VB6 Integer is a C# short
  • A VB6 Long is a C# int
  • A VB6 Boolean is a C# short with -1 = True, 0 = False;
  • VB6 strings have a fixed width, you need to read them as byte[]

Ought to be enough to solve the problem. And of course keep in mind that it is very simple to use a VB.NET assembly from a C# program.

Upvotes: 4

Related Questions