using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace C16_1
{
[Serializable]
public class Login
{
private string s_username;
private string s_passworld;
[NonSerialized]
private string s_userid;
public string UserName
{
get { return s_username; }
set { this.s_username = value; }
}
public string PassWorld
{
get { return s_passworld; }
set { this.s_passworld = value; }
}
public string UserID
{
get { return s_userid; }
set { this.s_userid = value; }
}
}
public class Test
{
///
///序列化
///
public void BinaryFormatterSerialize()
{
Login login = new Login();
login.UserName = "admin";
login.PassWorld = "123456";
login.UserID = "s2";
FileStream fileStream = new FileStream("c:\\User.dat",FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
//將一個物件圖移位元組的順序持久化到一個指定資料流
b.Serialize(fileStream,login);
fileStream.Close();
}
///
///反序列化
///
public void BinaryFormatterDeSerialize()
{
Login login = new Login();
login.UserName = "Jim";
FileStream fileStream = new FileStream("c:\\User.dat",FileMode.Open,FileAccess.Read, FileShare.Read);
BinaryFormatter b = new BinaryFormatter();
//將一個持久化位元組順序轉化為一個物件圖
login = b.Deserialize(fileStream) as Login;
Console.WriteLine(login.UserName);
Console.WriteLine(login.PassWorld);
Console.WriteLine(login.UserID);
fileStream.Close();
}
public static void Main()
{
Test test = new Test();
test.BinaryFormatterSerialize();
test.BinaryFormatterDeSerialize();
}
}
}
沒有留言:
張貼留言