Imports System.Xml.Serialization
Imports System.Runtime.Serialization
Imports System.IO
Module Module2
Public Sub saveFile(ByVal filename As String)
Dim filestream As FileStream = New FileStream(AppDomain.CurrentDomain.BaseDirectory & filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim streamw As StreamWriter = New StreamWriter(filestream)
Dim stu As New Student(1, "唐伯虎", 96)
Dim ser As XmlSerializer = New XmlSerializer(GetType(Student))
ser.Serialize(streamw, stu)
streamw.Close()
filestream.Close()
Console.WriteLine("序列化完成!")
Console.ReadLine()
End Sub
Public Sub openFile(ByVal filename As String)
Dim filestream As FileStream = New FileStream(AppDomain.CurrentDomain.BaseDirectory & filename, FileMode.Open, FileAccess.Read)
Dim streamr As StreamReader = New StreamReader(filename)
Dim dser As XmlSerializer = New XmlSerializer(GetType(Student))
Dim stu As Student = CType(dser.Deserialize(streamr), Student)
Console.WriteLine("文件已經打開")
System.Threading.Thread.Sleep(1000)
Console.WriteLine(stu.Sid.ToString())
Console.WriteLine(stu.Sname)
Console.WriteLine(stu.Score.ToString())
Console.ReadLine()
End Sub
Public Sub binarySaveFile(ByVal filename As String)
Dim filestream As FileStream = New FileStream(AppDomain.CurrentDomain.BaseDirectory & filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim streamw As StreamWriter = New StreamWriter(filestream)
Dim stu As New Student()
With stu
.Sid = 2
.Sname = "祝枝山"
.Score = 97
End With
Dim binaryser As Formatters.Binary.BinaryFormatter = New Formatters.Binary.BinaryFormatter()
binaryser.Serialize(filestream, stu)
Console.WriteLine("序列化完成!")
Console.ReadLine()
End Sub
Public Sub binaryOpenFile(ByVal filename As String)
Dim filestream As FileStream = New FileStream(AppDomain.CurrentDomain.BaseDirectory & filename, FileMode.Open, FileAccess.Read, FileShare.Read)
Dim stu As New Student
Dim binaryDser As Formatters.Binary.BinaryFormatter = New Formatters.Binary.BinaryFormatter()
stu = binaryDser.Deserialize(filestream)
Console.WriteLine("反序列化完成")
System.Threading.Thread.Sleep(1000)
Console.WriteLine(stu.Sid.ToString())
Console.WriteLine(stu.Sname)
Console.WriteLine(stu.Score)
Console.ReadLine()
End Sub
Public Sub Main()
'saveFile("sample.txt")
'openFile("sample.txt")
'binarySaveFile("sample.txt")
binaryOpenFile("sample.txt")
End Sub
End Module
沒有留言:
張貼留言