首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實作 QQ 自動登入器(四):二進位序列化儲存用戶資訊

     編輯:關於C語言

序列化需求

支援多用戶登入器規劃,預留集合序列化介面。使用 `BinaryFormatter` 將 `UserInfo` / `List` 序列化為 `UserInfo.bin`,儲存於應用程式啟動目錄。

核心類別 `SerializeHelper`

單一物件序列化/反序列化


public static void SerializeUserInfo(UserInfo ui)
{
    try
    {
        using (var fs = new FileStream(Path.Combine(Application.StartupPath, "UserInfo.bin"), FileMode.Create))
        {
            new BinaryFormatter().Serialize(fs, ui);
        }
    }
    catch (Exception ex) { MessageBox.Show(ex.Message); }
}

public static UserInfo DeserializeUserInfo()
{
    try
    {
        using (var fs = new FileStream(Path.Combine(Application.StartupPath, "UserInfo.bin"), FileMode.Open))
        {
            return (UserInfo)new BinaryFormatter().Deserialize(fs);
        }
    }
    catch { return null; }
}

泛型集合序列化/反序列化


public static void SerializeList(List list)
{
    try
    {
        using (var fs = new FileStream(Path.Combine(Application.StartupPath, "UserInfo.bin"), FileMode.Create))
        {
            new BinaryFormatter().Serialize(fs, list);
        }
    }
    catch (Exception ex) { MessageBox.Show(ex.Message); }
}

public static List DeserializeList()
{
    try
    {
        using (var fs = new FileStream(Path.Combine(Application.StartupPath, "UserInfo.bin"), FileMode.Open))
        {
            return (List)new BinaryFormatter().Deserialize(fs);
        }
    }
    catch (Exception ex) { MessageBox.Show(ex.Message); return null; }
}

關鍵實作細節

  • `using` 區塊確保 `FileStream` 正確釋放,避免檔案鎖定。
  • `Path.Combine` 替代字串串接,跨平台相容。
  • 反序列化失敗回傳 `null`,上層邏輯判斷為首次執行。
  • 集合方法預留多用戶擴展,單用戶版僅使用單一物件版本。

安全性與版本控制警示

  • `BinaryFormatter` **已被標記為不安全**(CVE-2021-44228 等反序列化漏洞),**.NET 5+ 已標記過時**。
  • 生產環境應改用 `System.Text.Json`、`XmlSerializer`、`protobuf-net` 等安全序列化器。
  • 若必須用 `BinaryFormatter`,需實作 `SerializationBinder` 限制反序列化型別白名單。
  • 檔案版本:新增欄位時舊檔反序列化會保留預設值,需在 `UserInfo` 實作 `ISerializable` 或 `OnDeserialized` 處理遷移。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved