在 VB6.0 和 VB.NET 中读写二进制文件的方式有所不同。以下是如何在这两种环境中进行二进制文件读写的详细说明。
在 VB6.0 中,可以使用 Open
、Get
和 Put
语句来读写二进制文件。
Private Sub WriteBinaryFile(filePath As String, data() As Byte)
Dim fileNum As Integer
fileNum = FreeFile
Open filePath For Binary Access Write As #fileNum
Put #fileNum, , data
Close #fileNum
End Sub
Private Function ReadBinaryFile(filePath As String) As Byte()
Dim fileNum As Integer
Dim fileLength As Long
Dim data() As Byte
fileNum = FreeFile
Open filePath For Binary Access Read As #fileNum
fileLength = LOF(fileNum)
ReDim data(fileLength - 1)
Get #fileNum, , data
Close #fileNum
ReadBinaryFile = data
End Function
在 VB.NET 中,可以使用 FileStream
和 BinaryReader
/BinaryWriter
类来读写二进制文件。
Imports System.IO
Private Sub WriteBinaryFile(filePath As String, data() As Byte)
Using fs As New FileStream(filePath, FileMode.Create, FileAccess.Write)
fs.Write(data, 0, data.Length)
End Using
End Sub
Imports System.IO
Private Function ReadBinaryFile(filePath As String) As Byte()
Using fs As New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim data(fs.Length - 1) As Byte
fs.Read(data, 0, data.Length)
Return data
End Using
End Function
领取专属 10元无门槛券
手把手带您无忧上云