I am creating XML file in C# and write data in it. But in case f exception the file should roll back. But in case of exception, file is generated with incomplete format and data. I just want that when exception generate the file should not be generated. i am using below code to generate file
using (XmlWriter writer = XmlWriter.Create(strFileName))
{
writer.WriteStartElement("Head");//Start Head
writer.WriteElementString("Date", dtm.ToString("yyyy-MM-dd hh:mm:ss.fff"));
writer.WriteEndElement();//End Head
writer.Flush();
}
The simplest approach is to just build the whole document up to start with in-memory, and then only write it at the very end. That will almost certainly lead to simpler code even leaving aside the "don't write invalid date" side of things. The only downside is if you want to write an enormous file which you don't want in memory first.
Personally I would recommend using LINQ to XML - and using its conversions for other types, so you might use:
element.Add(new XElement("Date", dtm));
... which would use a correct XML date/time format rather than the one you've currently got (which uses hh
instead of HH
; see my blog post on date/time text conversions for more information about similar common mistakes).
See more on this question at Stackoverflow