0

I am writing to ask you about such question. So i have method which writes exception's info into xml file, but if some exception processed, this method replace all that it is in that file. I want that method write to end file a new info about exception Code of my method is given below:

public void WriteIntoFile()
        {
            XDocument xdoc = new XDocument(
            new XElement("Exceptions",
                new XElement("Exception",
                    new XElement("Message",this.ErrorMessage.ToString())
                   )));

            xdoc.Save("1.xml");
        }

Please, help me with it

Y.Wonder
  • 39
  • 4
  • 1
    See [Appending an existing XML file](http://stackoverflow.com/questions/2645440/appending-an-existing-xml-file). But i would recommend using a logging framework like [NLog](http://nlog-project.org/). – Georg Patscheider Jul 18 '16 at 08:38
  • Are you sure that writing your own logging framework is the best approach? You'll need to consider performance when the log file gets large, as well as deciding what to do if the disk gets full, or if you want to create a new log file every day, or when the log file gets above a certain size. This problem has been solved by multiple logging frameworks already. As well as NLog, you could also consider [log4net](https://logging.apache.org/log4net/). – Richard Ev Jul 18 '16 at 08:54

1 Answers1

0

This should do the Job, assuming the file exists and you create a new node call "Exceptions".

    public void WriteIntoFile(string Message)
    {
        const string Path = "C:\\Temp\\Log.xml";

        XmlDocument MyDocument = new XmlDocument();
        MyDocument.Load(Path);

        XmlNode ExceptionsNode = MyDocument.CreateElement("Exceptions");
        XmlNode ExceptionNode = MyDocument.CreateElement("Exception");
        XmlNode MessageNode = MyDocument.CreateElement("Message");

        MessageNode.InnerText = Message;

        ExceptionNode.AppendChild(MessageNode);
        ExceptionsNode.AppendChild(ExceptionNode);

        MyDocument.AppendChild(ExceptionsNode);
    }

if you want the "Exception"- Node append to a existing "Exceptions" node, use this:

        XmlNode ExceptionsNode = MyDocument.SelectSingleNode("/Exceptions");

Greetings from Austria.

Essigwurst
  • 555
  • 10
  • 24