記住用戶的密碼,一般瀏覽器都有這個功能,基於C/S結構的軟件實現這個功能也有很多方法,這裏採用簡單的文件流保存用戶名及密碼的方法來實現這個功能。
Person類,模擬用戶
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LMSys.Model
{
/// <summary>
/// 用戶基類
/// </summary>
[Serializable]
public class Person
{
#region 屬性
/// <summary>
/// 用戶名
/// </summary>
string userName;
public string UserName
{
get { return userName; }
set { userName = value; }
}
/// <summary>
/// 密碼
/// </summary>
string userPassword;
public string UserPassword
{
get { return userPassword; }
set { userPassword = value; }
}
/// <summary>
/// 權限
/// </summary>
int power;
public int Power
{
get { return power; }
set { power = value; }
}
#endregion
}
}
RememberUser類,記住用戶,但採用的是二進制的方式保存數據
using LMSys.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace LMSys.BLL
{
public class RememberUser
{
private static Dictionary<string, Person> persons = new Dictionary<string, Person>();
/// <summary>
/// 構造函數,讀取文件流
/// </summary>
public RememberUser()
{
FileStream fs = new FileStream("Data.bin", FileMode.OpenOrCreate);
if (fs.Length > 0)
{
BinaryFormatter bf = new BinaryFormatter();
persons = bf.Deserialize(fs) as Dictionary<string, Person>;
}
fs.Close();
}
/// <summary>
/// 返回保存的用戶列表
/// </summary>
/// <returns></returns>
public Dictionary<string, Person> GetList()
{
return persons;
}
/// <summary>
/// 添加新用戶
/// </summary>
/// <param name="person"></param>
public void AddRemember(Person person)
{
FileStream fs = new FileStream("Data.bin", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
if (persons.ContainsKey(person.UserName))//若已存在用戶,先移除該用戶
{
persons.Remove(person.UserName);
}
persons.Add(person.UserName, person);//再添加該用戶,防止用戶密碼更新
bf.Serialize(fs, persons);
fs.Close();
}
}
}
這樣,界面就可以很容易調用該類實現記住密碼的功能。