最近工作需要写一个小工具,对会员卡卡号进行修改,需要修改的会员卡号存放在excel中,其中有id,正确卡号,当前错误卡号,状态 4列,为了不让用户随意修改excel内容,需要将excel转化为xml,然后对xml进行加密,在程序中读取xml内容,放到字符串中,进行解密,然后在读卡后,查找xml是否有对应的错误卡号,如果有将卡号修改为正确卡号,然后修改成功后需要将这张卡的状态置为已修改。
<?xml version="1.0" encoding="UTF-8"?>
<CardsInfo>
<Card ID="1" CorrectCardNum="201603011" ErrorCardNum="20163011" Satus="" />
<Card ID="2" CorrectCardNum="201603012" ErrorCardNum="20163012" Satus="" />
......
</CardsInfo>
到目前为止,我们用的aes.xml是乱码的,用户不知道这个文件xml存了什么,相对安全
//下面是读取aes.xml,解密,将信息存到list,并展示到datagridview中
/// <summary>
/// 将xml解密,并将信息存放到list,且展示在gridview List<CardInfo>
/// </summary>
private void decryptionXml()
{
List<CardInfo> cardInfoList = new List<CardInfo>();
XmlDocument xdoc = new XmlDocument();
XmlNodeList xnlist = explainXmlStr(ref xdoc);
foreach (XmlNode xn in xnlist)
{
CardInfo ci = new CardInfo();
XmlElement xe = (XmlElement)xn;
ci.ID = xe.GetAttribute("ID").ToString();
ci.CorrectCardNum = xe.GetAttribute("CorrectCardNum").ToString();
ci.ErrorCardNum = xe.GetAttribute("ErrorCardNum").ToString();
ci.Satus = xe.GetAttribute("Satus").ToString() == "" ? "未修正" : "已修正";
cardInfoList.Add(ci);
}
dataGridView_card.DataSource = cardInfoList;
dataGridView_card.Columns[0].HeaderText = "ID";
dataGridView_card.Columns[1].HeaderText = "正确卡号";
dataGridView_card.Columns[2].HeaderText = "错误卡号";
dataGridView_card.Columns[3].HeaderText = "状态";
}
/// <summary>
/// 读取加密的xml,解密,解析成XmlNodeList
/// </summary>
/// <returns></returns>
private XmlNodeList explainXmlStr(ref XmlDocument xdoc)
{
string content = File.ReadAllText(dir).ToString();//读取xml文件内容
string AESDecryptStr = AES.AESDecrypt(content);//xml解密后字符串
xdoc = new XmlDocument();
xdoc.LoadXml(AESDecryptStr);
XmlNode xnode = xdoc.SelectSingleNode("CardsInfo");
XmlNodeList xnlist = xnode.ChildNodes;
return xnlist;
}
//修改xml 中某节点信息,保存
private void modify()
{
XmlDocument xml = new XmlDocument();
XmlNodeList xnlist = explainXmlStr(ref xml);
foreach (XmlNode xn in xnlist)
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("ErrorCardNum").ToString()==CardNum) //查到对应节点
{
if (cardID.Write(xe.GetAttribute("CorrectCardNum").ToString()))//修改会员卡卡号
{
xe.SetAttribute("Satus","已修改");//将xml对应节点的状态修改为已修改
SaveXmlStr(xml);
WriteLog(filename, CardNum, "Success");//记录日志
}
/// <summary>
/// 保存修改后的xml对象
/// </summary>
/// <param name="xd"></param>
private void SaveXmlStr(XmlDocument xd)
{
string xmlStr = xd.InnerXml.ToString();//xml内容
string aesCardInfo = AES.Encrypt(xmlStr);//加密
//string dd = AES.AESDecrypt(aesCardInfo);
FileStream fs = new FileStream(dir, FileMode.Create);//在dir路径下覆盖原来的xml文件
StreamWriter sw = new StreamWriter(fs);
sw.Write(aesCardInfo);
sw.Flush();
sw.Close();
decryptionXml();//修改后重新加载gridview
}
private void CopySetting()
{
string sourcePath = "D:\软件\管理系统\Config\Settings.xml";//要复制的源文件
string destPath = Path.Combine(System.Windows.Forms.Application.StartupPath, "Config\Settings.xml");//目标路径文件名
if (File.Exists(destPath ))
File.Delete(destPath );
System.IO.File.Copy(sourcePath , destPath );
}