Xml file content is lost if ...

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.
 
M

Matt Berther

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;
}
 
G

Guest

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?
 
M

Matt Berther

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. ;)
 
G

Guest

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top