SerializeHelper.cs 序列化類,打算做多用戶登錄器呢,就預留了兩個用來序列化集合的方法
Code
[copy to clipboard]
CODE:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;//序列化
using System.IO;
namespace QQLogin
{
/**//// <summary>
/// 序列化幫助類
/// </summary>
class SerializeHelper
{
/**//// <summary>
/// 使用反序列化方式讀取信息
/// </summary>
/// <returns></returns>
public static UserInfo DeserializeUserInfo()
{//將用戶信息使用反序列化方式提取
UserInfo ui = null;
try
{
FileStream fileStream = null;
fileStream = new FileStream(Application.StartupPath + "\\UserInfo.bin", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
ui = (UserInfo)bf.Deserialize(fileStream);
fileStream.Close();
}
catch (Exception ex)
{
}
return ui;
}
/**//// <summary>
/// 序列化UserInfo對象
/// </summary>
/// <param name="ui">傳入要序列化的UserInfo對象</param>
public static void SerializeUserInfo(UserInfo ui)
{//將用戶信息使用序列化方式保存
try
{
FileStream fileStream = null;
fileStream = new FileStream(Application.StartupPath + "\\UserInfo.bin", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fileStream, ui);
fileStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/**//// <summary>
/// 反序列化UserInfo泛型集合對象
/// </summary>
/// <returns></returns>
public static List<UserInfo> DeserializeList()
{//將用戶信息使用反序列化方式提取
List<UserInfo> lst = null;
FileStream fileStream = null;
try
{
fileStream = new FileStream(Application.StartupPath + "\\UserInfo.bin", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
lst = (List<UserInfo>)bf.Deserialize(fileStream);
fileStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return lst;
}
/**//// <summary>
/// 序列化UserInfo泛型集合對象
/// </summary>
/// <param name="ui">傳入要序列化的List<UserInfo>對象</param>
public static void SerializeList(List<UserInfo> lst)
{//將用戶信息使用序列化方式保存
FileStream fileStream = null;
try
{
fileStream = new FileStream(Application.StartupPath + "\\UserInfo.bin", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fileStream, lst);
fileStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}