我需要创建一个包含二进制输入的文件,但是当我这样做时,它需要字节而不是位
例如,如果我想添加“apple”的二进制表示 它写入文件0110000101110000011100000110110001100101它包含40位 但是,当我查看文件时,它显示40bytes,因为它将每个位作为char,因此它按字节方式保存。 我如何防止这种情况并在VB.net中逐位保存所有信息?
Dim fs As New FileStream("\binfile.bin", FileMode.Append)
Dim bw As New BinaryWriter(fs)
Dim TempStr As String
For t As Integer = 0 To Nameoftable.Length - 1
Dim bin As String = _
LongToBinary(Asc(Nameoftable.Substring(t, 1))) 'BIT CONVERTER FUNCTION
TempStr &= bin.Substring(bin.Length - 8)
Next t
bw.Write(TempStr)
bw.Close()
非常感谢...
答案 0 :(得分:1)
您必须使用BINARY读取器/写入器对象,并指定发送到写入流的数据的字段类型,并且读取器中从流中读取的数据也是如此。
Dim filename As String = "c:\temp\binfile.bin"
Dim writer As BinaryWriter
Dim reader As BinaryReader
Dim tmpStringData As String
Dim tmpByteData As Byte
Dim tmpCharData As Char
Dim tempIntData as Integer
Dim tempBoolData as Boolean
'
writer = New BinaryWriter(File.Open(filename, FileMode.Append))
Using writer
writer.Write("apple")
'writer.Write(YourByteDataHere) 'byte
'writer.Write(YourCharHere) 'char
'writer.Write(1.31459) 'single
'writer.Write(100) 'integer
'writer.Write(False) 'boolean
End Using
writer.Close()
'
If (File.Exists(filename)) Then
reader = New BinaryReader(File.Open(filename, FileMode.Open))
Using reader
tmpStringData = reader.ReadString()
'tempByteData = reader.ReadByte()
'tempCharData = reader.ReadChar()
'tempSingleData = reader.ReadSingle()
'tempIntData = reader.ReadInt32()
'tempBoolData = reader.ReadBoolean()
End Using
reader.Close()
End If
我用ReadString()方法写了字符串“apple” 如果您愿意,可以使用字符或字节的chr代码,在这种情况下,您必须使用ReadByte()或ReadChar()或ReadInt(),具体取决于您将其发送到流的方式(作为字节,字符或整数)
因此文件流处理程序自己内部使用的文件大小为6字节1,而'apple'为文件大小为5
如果你把它保存为char或byte,我会认为它使用的是5个字节,1k长 如果你把它保存为整数,我会认为它使用的是10个字节,而且是1k长
参考:http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx