在實際應用中,使用者可能需要ERP記錄密碼,不想每次登入的時候都輸入,就像qq一樣.
下面是C#的代碼:
先引用以下命名空間
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Management;using System.Windows.Forms;using System.IO;using System.Xml;using System.Xml.Linq;
具體代碼如下:
/// <summary> /// 儲存登入密碼 /// </summary> /// <param name="diskid">硬碟id</param> /// <param name="deptid">部門id</param> /// <param name="uid">使用者名稱</param> /// <param name="pwd">密碼</param> /// <param name="IsSave">是否儲存</param> /// <returns></returns> public bool SavePassword(string diskid, int deptid, string uid, string pwd, bool IsSave) { bool flag = false; try { string xmlfile = Application.StartupPath + "\\user.xml"; if (!File.Exists(xmlfile)) { XDocument xdoc = new XDocument(); xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes") , new XElement("Users" , new XAttribute("Id", diskid))); xdoc.Save(xmlfile); } XDocument doc = XDocument.Load(xmlfile); XElement xe = doc.Element("Users"); if (diskid == xe.Attribute("Id").Value.ToString()) { //先尋找是否已經儲存這個使用者 var pwds = from un in xe.Descendants("Dept") where un.Attribute("Id").Value == deptid.ToString() && un.Attribute("UserName").Value == uid select un; //如果是儲存則修改尋找到的使用者名稱、密碼或添加使用者名稱、密碼節點 if (IsSave) { if (pwds.Count() > 0) { foreach (var node in pwds) { node.Attribute("PassWord").Value = pwd; } } else { XElement xel = new XElement("Dept"); xel.Add(new XAttribute("Id", deptid)); xel.Add(new XAttribute("UserName", uid)); xel.Add(new XAttribute("PassWord", pwd)); xe.Add(xel); } } else { if (pwds.Count() > 0) { //刪除儲存的帳號及密碼 XElement node = (XElement)pwds.SingleOrDefault(); node.Remove(); } } doc.Save(xmlfile); } } catch (Exception ex) { flag = false; } return flag; }
下面是讀取使用者的密碼:
/// <summary> /// 讀取儲存的使用者密碼 /// </summary> /// <param name="diskid">硬碟id</param> /// <param name="deptid">部門id</param> /// <param name="uid">使用者名稱</param> /// <returns></returns> public string ReadPassword(string diskid, int deptid, string uid) { string pwd = ""; try { string xmlfile = Application.StartupPath + "\\user.xml"; if (!File.Exists(xmlfile)) { return ""; } XDocument doc = XDocument.Load(xmlfile); XElement xe = doc.Element("Users"); //先尋找是否已經儲存這個使用者 var pwds = from un in xe.Descendants("Dept") where un.Attribute("Id").Value == deptid.ToString() && un.Attribute("UserName").Value == uid select un; if (pwds.Count() > 0) { foreach (var node in pwds) { pwd= node.Attribute("PassWord").Value ; } } } catch (Exception ex) { pwd = ""; } return pwd; }