Xml file content is lost if ...

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

In the following snippet if an error occurs after XmLTextWriter is
instantiated I will lose the content of my Xml file!

// validation ...
// writing data into dataset
dataSet.AcceptChanges();
XmlTextWriter xmlWriter = new XmlTextWriter("myFile.xml", Encoding.UTF8);
throw new Exception("say an error occured here");
dataSet.WriteXml(xmlWriter);

How can I prevent this?

Thank you.
 
Hello Nad,

You could use try/catch:

XmlTextWriter xmlWriter = new XmlTextWriter("myFile.xml", Encoding.UTF8);
try
{
throw new Exception("say an error occured here");
}
catch (Exception e)
{
dataSet.WriteXml(xmlWriter);
throw;
}
 
That does it yes. But In my humble opinion, it doesn't look nice to write to
xml inside a catch block. But what if something goes wrong with WriteXml
itself?
 
Hello Nad,

I agree... Im guessing that if something happens while you're creating your
xml, you probably also dont want to do the dataset.WriteXml, because presumably
something went wrong with the xml generation.

I only provided the code sample to answer your question. ;)
 
Matt,

I understand. The only thing I came up with is just to copy the file inti
whater.bak.xml while I'm reading it. This way at least I'll only lose one
session's data!
Thanks for your reply.
 
Back
Top