Pages

Men

rh

6/17/2012

Error Logging in XML using C#


using System.IO;
using System.Xml;

 
 public void WriteXmlErrorLog(String errdate, String errmessage, String classname, String methodname)
        {
            string path = @"C:\Program Files\PrideSysTech\Log\ErrLogfile.Xml";
            if (File.Exists(path))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlElement newchild = doc.CreateElement("Error");

                XmlElement datechild = doc.CreateElement("Date");
                datechild.InnerText = errdate.ToString();
                newchild.AppendChild(datechild);

                XmlElement errmessagechild = doc.CreateElement("ErrorMessage");
                errmessagechild.InnerText = errmessage.ToString();
                newchild.AppendChild(errmessagechild);

                XmlElement classnamechild = doc.CreateElement("ClassName");
                classnamechild.InnerText = classname.ToString();
                newchild.AppendChild(classnamechild);

                XmlElement methodnamechild = doc.CreateElement("MethodName");
                methodnamechild.InnerText = methodname.ToString();
                newchild.AppendChild(methodnamechild);


                doc.DocumentElement.InsertAfter(newchild, doc.DocumentElement.LastChild);
                doc.Save(path);
            }
            else
            {
                XmlTextWriter tw = new XmlTextWriter(path, null);
                tw.Formatting = Formatting.Indented;
                tw.WriteStartDocument();
                tw.WriteStartElement("ErrRoot");
                tw.WriteStartElement("Error");
                tw.WriteStartElement("Date");
                tw.WriteString(errdate.ToString());
                tw.WriteEndElement();

                tw.WriteStartElement("ErrorMessage");
                tw.WriteString(errmessage.ToString());
                tw.WriteEndElement();

                tw.WriteStartElement("ClassName");
                tw.WriteString(classname.ToString());
                tw.WriteEndElement();

                tw.WriteStartElement("MethodName");
                tw.WriteString(methodname.ToString());
                tw.WriteEndElement();

                tw.WriteEndElement();
                tw.WriteEndElement();
                tw.WriteEndDocument();
                tw.Flush();
                tw.Close();

            }

        }

No comments :

Post a Comment