快速写入Xml文件
我们在做一些操作的时候会需要生成日志,Xml文件就是我们常用的一种日志文件。
普通操作Xml文件的代码遇到大数据量的话就很慢了。
用这个生成Xml文件的话,即使数据量很大,也很快
1 private void WriteXml(BindingList<Model.WebServiceLog> listwebservicelog, string XName) 2 { 3 DateTime dtNow = Globas.Globas.DtNowTime; ; 4 string dateString = dtNow.Year.ToString(); 5 dateString += dtNow.Month.ToString().Length < 2 ? ("0" + dtNow.Month.ToString()) : (dtNow.Month.ToString()); 6 dateString += dtNow.Day.ToString().Length < 2 ? ("0" + dtNow.Day.ToString()) : (dtNow.Day.ToString()); 7 8 string filePath = ConfigurationManager.AppSettings["path"]; 9 filePath = filePath.EndsWith(@"\") ? filePath : (filePath + @"\"); 10 filePath = filePath + dateString; 11 filePath = filePath.EndsWith(@"\") ? filePath : (filePath + @"\"); 12 13 if (Directory.Exists(filePath) == false) 14 { 15 Directory.CreateDirectory(filePath);//判断该路径是否存在,不存在则创建该路径文件夹 16 } 17 18 filePath = filePath + XName + DateTime.Now.ToString("yyyyMMdd") + ".xml"; 19 String filename = String.Concat(filePath); 20 using (StreamWriter sw = new StreamWriter(filename, true, System.Text.Encoding.GetEncoding("UTF-8"))) 21 { 22 XmlTextWriter xmlWriter = new XmlTextWriter(sw); 23 xmlWriter.Formatting = Formatting.Indented; 24 xmlWriter.WriteStartDocument(); 25 xmlWriter.WriteStartElement("Logs"); 26 27 foreach (Model.WebServiceLog webservicelog in listwebservicelog) 28 { 29 xmlWriter.WriteStartElement("Log"); 30 xmlWriter.WriteElementString("UseDate", webservicelog.UseDate); 31 xmlWriter.WriteElementString("Method", webservicelog.Method); 32 xmlWriter.WriteElementString("Parameter", webservicelog.Parameter); 33 xmlWriter.WriteElementString("UseOrReturn", webservicelog.UseOrReturn); 34 // close contact </contact> 35 xmlWriter.WriteEndElement(); 36 } 37 // close contacts </contact> 38 xmlWriter.WriteEndElement(); 39 xmlWriter.WriteEndDocument(); 40 xmlWriter.Close(); 41 } 42 }
调用方式:
1 WriteXml(listWebservice, "Info_");