Solved

how to append a xml file in c# if exists, or make new if not?

Posted on 2010-11-22
7
860 Views
Last Modified: 2012-05-10
i am adding tracing for audit purposes of a simple process i have built as an .exe and set in the scheduler to run every 10 minutes. i want to have the application output the results into an xml file.

if the file exists then open and append data to it, if it does not exist i want to create a new xml file that will be persisted and used on next run.

here is my code now, what do i need to add, how do i open the xml file (on c:/file.xml) and use it to append nodes to?

also i think my code is like a newbs, so some help in showing me the correct streamlined way would help me learn best practice with C#/ XML

string err = "";
        XmlDocument doc = new XmlDocument();// Create the XML Declaration, and append it to XML document

        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
        doc.AppendChild(dec);// Create the root element

        XmlElement root = doc.CreateElement("STATS");
        doc.AppendChild(root);

        // Create URL's            
        XmlElement urlNode = doc.CreateElement("keepalive");
        urlNode.SetAttribute("runTime", DateTime.Now.ToString());

        try
        {
            WebProxy wp = new WebProxy("http://proxy.ml.com:8083/");
            WebClient w = new WebClient();
            w.Proxy = wp;

            if (w.DownloadString("http://wwww.idealcoding.com") != "")
                urlNode.SetAttribute("result", "UP");
            else
                urlNode.SetAttribute("result", "DOWN");
        }
        catch (Exception ex)
        {
            err = ex.Message;
            urlNode.SetAttribute("result", "DOWN");
        }
        finally {
            root.AppendChild(urlNode);
            doc.Save("c:/keepAlive.xml");
        }

Open in new window



this is my XML file:
 
<STATS>
  <keepalive runTime="11/22/2010 9:40:43 AM" result="UP" /> 
 </STATS>

Open in new window

0
Comment
Question by:realcoding
  • 3
  • 2
  • 2
7 Comments
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 34188933
What is it you want to add to the file, a new <STATS /> everytime it runs or a new <keepalive /> adding to STATS?
0
 

Author Comment

by:realcoding
ID: 34189033
i want to just add keepalive nodes, such that each run of the app will log the time it ran and result.
if the file exists i want to load it into the xml object and add a keepalive node with the current runs info and so on... if the xml file does not exist then do as i do here and create a new one.

but as it stands every run of the app creates and over-writes the xml file leaving only one node , not very useful.
0
 
LVL 18

Assisted Solution

by:Richard Lee
Richard Lee earned 200 total points
ID: 34189081
Okay the approach I would take here, and its a slightly different thinking from you is that I would have a Xml Serializable Audit object. I would then read the contents of the file and deserialize into and instance of the Audit class and then add the new entries to this object and overwrite the existing file.

Xml Serializer and Deserializer class:
http://avantprime.com/articles/view-article/13/xml-serialization-and-de-serialization-helper-class-using-generics

Use the StreamReader and StreamWriter classes to manipulate the file on disk.
http://www.c-sharpcorner.com/UploadFile/puranindia/StreamReaderStreamWriterClasses11242009235459PM/StreamReaderStreamWriterClasses.aspx

DaTribe
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 52

Accepted Solution

by:
Carl Tawn earned 300 total points
ID: 34189085
OK, try replacing these four lines:
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
        doc.AppendChild(dec);// Create the root element

        XmlElement root = doc.CreateElement("STATS");
        doc.AppendChild(root);

Open in new window

With:
    XmlElement root;

   if (File.Exists(@"c:\keepAlive.xml"))
   {
         doc.Load(@"c:\keepAlive.xml");
         root = doc.SelectSingleNode("/STATS");
   }
   else
   {
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
        doc.AppendChild(dec);// Create the root element

        root = doc.CreateElement("STATS");
        doc.AppendChild(root);
   }

Open in new window


You may also want to move the filename into a variable to save you typing it over and over again.
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 34189103
Also to handle when this file gets very large I would write to a new write each hour / day. You could create folders for further organization. File would be suffixed with Date & Time. Folders would be suffixed with Date.

DaTribe
0
 

Author Closing Comment

by:realcoding
ID: 34189826
why would you use a serializable object? whats the gain?
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 34189903
The gain for me would be simply manipulating this object easily with c# and then in the end simply turning it back to XML. Avoid the hassles with XML plus another huge bonus would be I could add or remove properties from the Audit class and deserialization would still be successful and as the file contents are over-written when saving then there would be no problem saving the new structure.

I save myself development time and hassles. More maintainable solution. In this instance as its every 10 minutes mission critical performance is not required - still some of the suggestions I provided work around that.

DaTribe
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Icons and Colors for Terms 3 24
AL3 Files 4 13
ASP.net Javascript use multiple sliders 2 18
Issue with XSLT mapping 10 15
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now