Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and write interoperable strings to a binary file between .NET and vb6

Tags:

c#

vb6

I have a new program I am writing in C#, it will need to read and write binary files that are compatible with vb6's binary format. I can not change the vb6 program but I can make changes to my program.

I have everything working except I am a little iffy about strings.

If I write the following in vb6

Private Type PatchRec
   string As String
End Type

Private Sub Command1_Click()
    Dim intFileNum As Integer
    Dim recTest As TestRec
    intFileNum = FreeFile
    Open "E:\testing" & "\" & "testfile" & ".bin" For Binary Access Write As #intFileNum
    recTest.string = "This is a test string"    
    Put #intFileNum, , recPatch
    Close #intFileNum
End Sub

And I write the following in C#

public static void Main(params string[] args)
{
    using(var fs = new FileStream("test.bin", FileMode.Create, FileAccess.ReadWrite))
    using (var bw = new BinaryWriter(fs))
    {
        string str = "This is a test string";
        bw.Write(str);
    }
}

I get these two hex strings

vb6 - 15 00 54 68 69 73 20 69 73 20 61 20 74 65 73 74 20 73 74 72 69 6E 67
c# -     15 54 68 69 73 20 69 73 20 61 20 74 65 73 74 20 73 74 72 69 6E 67

It appears BinaryWriter is not the same between the two when writing strings, vb6 uses a two byte string and C# uses a UTF-7 encoded unsigned int. Also I can not find any resource to what encoding VB is using when it writes a file this way.

Are there any built in tools to write the same way vb6 does and if not other than turning the length in to a uint16 are there any other gotchas I need to be aware of?

like image 802
Scott Chamberlain Avatar asked Nov 07 '11 21:11

Scott Chamberlain


1 Answers

It is simply a short that contains the string length, use BinaryWriter(short). Don't use BinaryWriter.Write(string), use BinaryWriter.Write(byte[]) where you got the byte[] from Encoding.Default.GetBytes().

Intentional avoiding the compat functions in the Microsoft.VisualBasic namespace might not the be most productive approach. It doesn't byte, the framework doesn't care what language you use. Have a look at Microsoft.VisualBasic.FileSystem.FilePut(). Available in any .NET framework version, that's code you won't have to maintain and has been tested by thousands. You do have to add an assembly reference to Microsoft.VisualBasic.

like image 168
Hans Passant Avatar answered Oct 12 '22 02:10

Hans Passant