1.写xml
/// <summary> /// 写错误日志 /// </summary> /// <param name="ex"></param> public static void WriteErrorLog(Exception ex) { DataTable dt = new DataTable("ErrorLog"); dt.Columns.Add("Date"); dt.Columns.Add("Message"); DataRow dr = dt.NewRow(); dr["Date"] = DateTime.Now; dr["Message"] = ex.Message; dt.Rows.Add(dr); string path = Config.GetConfigValue("BASE_ERROR_FOLDER");//路径 //目录是否存在 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string fullPath = path + "errorLog.xml"; //文件是否存在 if (!File.Exists(fullPath)) { dt.WriteXml(fullPath, XmlWriteMode.WriteSchema); } else { AppandXml(ex, fullPath);//存在,则追加 } }
2.追加数据
/// <summary> /// 追加写入XML文件 /// </summary> /// <param name="ex"></param> /// <param name="fullPath">文件全路径</param> public static void AppandXml(Exception ex, string fullPath) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fullPath); XmlNode root = xmlDoc.SelectSingleNode("NewDataSet");//查找到根目录 XmlElement errorLog_ele = xmlDoc.CreateElement("ErrorLog"); XmlElement date_ele = xmlDoc.CreateElement("Date"); date_ele.InnerText = DateTime.Now.ToString(); errorLog_ele.AppendChild(date_ele); XmlElement message_ele = xmlDoc.CreateElement("Message"); message_ele.InnerText =ex.Message; errorLog_ele.AppendChild(message_ele); root.AppendChild(errorLog_ele); xmlDoc.Save(fullPath); }
3.读数据
string filePath = (string)(Config.GetDataPath(StatType, Year, Week)); DataTable dt = new DataTable(); dt.ReadXml(filePath);