简体   繁体   English

在C#中出现异常的情况下如何回滚XML文件

[英]How to roll back XML file in case of exception in c#

I am creating XML file in C# and write data in it. 我正在C#中创建XML文件并在其中写入数据。 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: 我个人建议使用LINQ to XML-并将转换用于其他类型,因此您可以使用:

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). ...将使用正确的 XML日期/时间格式,而不是您当前使用的格式(使用hh而不是HH ;有关类似的常见错误的更多信息,请参阅我的博客文章中的日期/时间文本转换 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM