Dim fs As New FileStream("1.txt", FileMode.Create)
Dim formatter As New BinaryFormatter
Try
formatter.Serialize(fs, P)
Catch e As SerializationException
Console.WriteLine("Failed to serialize. Reason: " & e.Message)
Throw
Finally
fs.Close()
End Try
End Sub
Sub Deserialize()
Dim p As Person = Nothing
Dim fs As New FileStream("1.txt", FileMode.Open)
Try
Dim formatter As New BinaryFormatter
p = formatter.Deserialize(fs)
Catch e As SerializationException
Console.WriteLine("Failed to deserialize. Reason: " & e.Message)
Throw
Finally
fs.Close()
End Try
Console.WriteLine("姓名:{0} 年龄:{1} 收入:{2}", p.Name, p.Age, p.Income)
End Sub
//Make a new FileStream object, exposing our data file.
//If the file exists, open it, and if it doesn't, then Create it.
FileStream fs = new FileStream("data.bin", FileMode.OpenOrCreate);
//create the reader and writer, based on our file stream
BinaryWriter w = new BinaryWriter(fs);
BinaryReader r = new BinaryReader(fs);
' Make a new FileStream object, exposing our data file.
' If the file exists, open it, and if it doesn't, then Create it.
Dim fs As FileStream = New FileStream("data.bin", FileMode.OpenOrCreate)
' create the reader and writer, based on our file stream
Dim w As BinaryWriter = New BinaryWriter(fs)
Dim r As BinaryReader = New BinaryReader(fs)
//make an appropriate receptacle for the information being read in...
//a StringBuilder is a good choice
StringBuilder output = new StringBuilder();
//set the file pointer to the beginning of our file...
r.BaseStream.Seek(0, SeekOrigin.Begin);
//continue to perform this loop while not at the end of our file...
while (r.PeekChar() > -1)
{
output.Append( r.ReadString() ); //use ReadString to read from the file
}
' make an appropriate receptacle for the information being read in...
' a StringBuilder is a good choice
Dim output as StringBuilder = New StringBuilder()
' set the file pointer to the beginning of our file...
r.BaseStream.Seek(0, SeekOrigin.Begin)
' continue to perform this loop while not at the end of our file...
Do While r.PeekChar() > -1
output.Append( r.ReadString() ) ' use ReadString to read from the file
Loop
' 因为不同数据类型之间的很多转换结果都是不可解释的,
' 所以当在其他类型与二进制数据之间进行转换时,
' 必须捕捉可能引发的任何潜在的异常...
' 能够正确读取数据依赖于如何写入信息...
' 这与写日志文件时不同。
Do While r.BaseStream.Position < r.BaseStream.Length ' 当未到达文件结尾时
Select Case selection
Case "Boolean"
output.Append( r.ReadBoolean().ToString() )
Case "String"
output.Append( r.ReadString() )
Case "Integer"
output.Append( r.ReadInt32().ToString() )
End Select
Loop
Finally
fs.Close()
End Try
return output.ToString()
End Function
Public Shared Function WriteFile(output As Object, selection As String) As String
Dim fs As FileStream = New FileStream("data.bin", FileMode.Create)
Dim w As BinaryWriter = New BinaryWriter(fs)
Dim strOutput As String = ""