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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With