日期:2014-05-17 浏览次数:21083 次
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace Test { [Serializable] public class Config { private static object objLock = new object(); private const string CONFIG_FILE = "Config.dat"; private static Config instance = new Config(); private Config() { } private string _name; private string _pwd; public static string UserName { set { instance._name = value; } get { return instance._name; } } /// <summary> /// 密码 (加密) /// </summary> public static string UserPwd { set { instance._pwd = value; } get { return instance._pwd; } } private void Serialize() { try { FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + CONFIG_FILE, FileMode.OpenOrCreate, FileAccess.ReadWrite); BinaryFormatter b = new BinaryFormatter(); b.Serialize(fileStream, this); fileStream.Close(); } catch (Exception ex) { } } private bool UnSerialize() { try { if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + CONFIG_FILE)) { FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + CONFIG_FILE, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryFormatter b = new BinaryFormatter(); Config c = (Config)b.Deserialize(fileStream); this._name = c._name; this._pwd = c._pwd; fileStream.Close(); return true; } } catch (Exception ex) { } return false; } /// <summary> /// 保存系统设定 /// </summary> public static void Save() { instance.Serialize(); } /// <summary> /// 载入系统初始化设定 /// </summary> public static void Load() { if (!instance.UnSerialize()) { instance._name = string.Empty; instance._pwd = string.Empty; instance.Serialize(); } instance.UnSerialize(); } } } // 保存 Config.UserName = "Leon382"; Config.UserPwd="**********" Config.Save(); // 取用 Config.Load(); string pwd=Config.UserPwd;
------解决方案--------------------
學習了