using System; using System.IO; using System.Windows.Forms; using System.Xml; using System.Data; namespace ziliaoruanjian { class ReadAndWriteXML { private static string path = Application.StartupPath + "\\recentlyFile.xml"; //高剑楠 2011-10-17 ###########判断目录下是否存在xml文件,并且进行写入 public static void AddFileName(string fileName) { //如果存在xml文件,则将打开的文件名称和时间存入 if (File.Exists(path)) { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(path); XmlNode root = xmldoc.SelectSingleNode("history"); XmlElement node = xmldoc.CreateElement("Project"); XmlElement nodeName = xmldoc.CreateElement("name"); nodeName.InnerText = fileName; XmlElement nodeDate = xmldoc.CreateElement("date"); nodeDate.InnerText = DateTime.Now.ToString(); node.AppendChild(nodeName); node.AppendChild(nodeDate); root.AppendChild(node); xmldoc.Save(path); } //如果不存在文件,则创建xml文件,再存入 else { CreateXmlFile(); AddFileName(fileName); } } //End高剑楠 //高剑楠 2011-10-17 ###########创建xml文件,用于存放最近打开的项目 private static void CreateXmlFile() { XmlDocument xmldoc = new XmlDocument(); XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null); xmldoc.AppendChild(xmldec); XmlElement root = xmldoc.CreateElement("history"); xmldoc.AppendChild(root); xmldoc.Save(path); } //End高剑楠 //高剑楠 2011-10-17 #############读取最近打开的项目名称 public static DataSet ReadFile() { //高剑楠 2011-10-20 ############当xml文件为空是判断 if (!File.Exists(path)) { CreateXmlFile(); return null; } //End 高剑楠 //先清理xml文件 ClearXml(); DataSet ds = new DataSet(); ds.ReadXml(path); return ds; } //End高剑楠 //高剑楠 2011-10-18 ##############当xml文件中储存内容大于5条时清理后5条意外的其他数据 private static void ClearXml() { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(path); //如果根节点下的子节点数大于5个,则删除时间最久的一个 if (xmldoc.SelectSingleNode("history").ChildNodes.Count>5) { DataSet ds = new DataSet(); ds.ReadXml(path); ds.Tables[0].Rows[0].Delete(); ds.WriteXml(path); } } //End 高剑楠 } }
学习笔记10(xml实现最近项目打开)
最新推荐文章于 2023-06-01 18:20:27 发布