0

在将 BinaryFile 反序列化为 Object 时出现上述错误。我尝试过 set position=0, seek.begin 方法并尝试使用内存流但没有用。每次我遇到同样的问题。任何人都可以帮助我吗?下面是我的序列化和反序列化代码片段

序列化

Dim fs As New FileStream(Filename, FileMode.OpenOrCreate)
Try

    'fs = New FileStream(Filename, FileMode.OpenOrCreate)
    Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
    bf.AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
    bf.TypeFormat = Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded
    bf.Serialize(fs, data)
Catch ex As Exception
    MsgBox("Exception: " & ex.Message & " | Stacktrace: " & ex.StackTrace)
Finally
    fs.Flush()
    fs.Close()
    fs.Dispose()

End Try

反序列化

Dim fs As FileStream = Nothing

Try
    fs = IO.File.OpenRead(Filename)
    'fs = New FileStream(Filename, FileMode.Open)

    Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()

    bf.AssemblyFormat = Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
    bf.TypeFormat = Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded
    fs.Seek(0, SeekOrigin.Begin) 'fs.Position=0
    Dim obj As Object = bf.Deserialize(fs)
    Return obj
Catch ex As Exception
    MsgBox("There was an exception while trying to convert binary file to object. Exception: " & ex.Message & " | Stacktrace: " & ex.StackTrace)
Finally
    If fs IsNot Nothing Then
        fs.Flush()
        fs.Close()
        fs.Dispose()
    End If
End Try
4

0 回答 0