从二进制文件读取并将字节数组转换为字符串

时间:2012-06-22 04:06:50

标签: vb.net binary-data

我正在尝试使用下面的代码从二进制文件中读取二进制数据,但它返回字节数组中的值。如何从二进制文件中读取二进制数据,然后将数据转换为字符串?

这是我创建二进制文件的方式。

Dim fs As New FileStream(Application.StartupPath & "\Agency.dat", FileMode.OpenOrCreate)
    Dim bf As New BinaryFormatter()
    Call bf.Serialize(fs, GAgency)
    fs.Close()

读取二进制文件的代码。

Public Shared Function ReadBinaryFile(ByVal path As String)
    ' Open the binary file.
    Dim streamBinary As New FileStream(path, FileMode.Open)

    ' Create a binary stream reader object.
    Dim readerInput As BinaryReader = New BinaryReader(streamBinary)

    ' Determine the number of bytes to read.
    Dim lengthFile As Integer = FileSize(path)

    ' Read the data in a byte array buffer.
    Dim inputData As Byte() = readerInput.ReadBytes(lengthFile)

    ' Close the file.
    streamBinary.Close()
    readerInput.Close()

    Return inputData
End Function 'ReadBinaryData’

1 个答案:

答案 0 :(得分:1)

尝试

Dim objGAgency As GAgency
Dim fs As Stream = New FileStream( Application.StartupPath & "\Agency.dat", FileMode.Open)
Dim bf As BinaryFormatter = New BinaryFormatter()

objGAgency = CType(bf.Deserialize(fs), GAgency)
fs.Close()