Wednesday, 25 January 2012

Storing Exception Messages into a folder using c#


    catch (Exception execp)
                    {
                        if (!System.IO.Directory.Exists(@"c:\flatfileerror"))
                            System.IO.Directory.CreateDirectory(@"c:\flatfileerror");

                        if (System.IO.File.Exists(@"c:\flatfileerror\error.xml"))
                        {
                            //System.IO.FileStream fs = System.IO.File.OpenWrite(@"c:\flatfileerror\error.xml");

                            XmlDocument doc = new XmlDocument();


                            doc.Load(@"c:\flatfileerror\error.xml");

                            XmlNode root = doc.DocumentElement;
                            XmlElement elem = doc.CreateElement("Message");
                            elem.InnerText = execp.Message.ToString();

                            //Add the node to the document.
                            root.AppendChild(elem);
                            if (!(execp.InnerException == null))
                            {
                                XmlElement eleme = doc.CreateElement("InnerException");
                                eleme.InnerText = execp.InnerException.ToString();

                                root.AppendChild(eleme);
                           
                            }
                            doc.Save(@"c:\flatfileerror\error.xml");

                        }
                        else
                        {
                            using (XmlWriter writer = XmlWriter.Create(@"c:\flatfileerror\error.xml"))
                            {
                                writer.WriteStartDocument();
                                writer.WriteStartElement("Error");
                                writer.WriteElementString("Message", execp.Message.ToString());
                                if (!(execp.InnerException == null))
                                    writer.WriteElementString("InnerException", execp.InnerException.ToString());

                                writer.WriteEndElement();

                                writer.WriteEndDocument();
                            }
                        }

                        MessageBox.Show("Error Ocurred, Please Check The Error.xml");

                    }

No comments:

Post a Comment