我有一个用C#编写的新程序,它需要读写与vb6二进制格式兼容的二进制文件.我无法更改vb6程序,但我可以更改我的程序.
我有一切工作,除了我对字符串有点不确定.
如果我在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
Run Code Online (Sandbox Code Playgroud)
我在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);
}
}
Run Code Online (Sandbox Code Playgroud)
我得到这两个十六进制字符串
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
Run Code Online (Sandbox Code Playgroud)
在编写字符串时,BinaryWriter看起来不一样,vb6使用两个字节的字符串,而C#使用UTF-7编码的unsigned int.此外,我无法找到任何资源来编写VB使用这种方式写入文件时使用的编码.
是否有任何内置工具以与vb6相同的方式编写,如果不是将长度转换为uint16,还有其他问题需要注意吗?
它只是一个包含字符串长度的short,使用BinaryWriter(short).不要使用BinaryWriter.Write(string),使用BinaryWriter.Write(byte [])从Encoding.Default.GetBytes()获取byte [].
故意避免使用Microsoft.VisualBasic命名空间中的compat函数可能不是最有效的方法.它不是字节,框架不关心你使用什么语言.看看Microsoft.VisualBasic.FileSystem.FilePut().可以在任何.NET框架版本中使用,这些代码您不必维护并且已经过数千次测试.您必须向Microsoft.VisualBasic添加程序集引用.