我在将BinaryFile反序列化为Object时遇到上述错误。我试过设置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