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
我在C#中创建XML文件并在其中写入数据。但是如果f异常,文件应该回滚。但是在异常的情况下,生成的文件格式和数据不完整。我只是想在异常生成文件时不应该生成。我使用下面的代码来生成文件
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();
}
1 个解决方案
#1
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;有关类似常见错误的更多信息,请参阅我在日期/时间文本转换的博客文章)。
#1
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;有关类似常见错误的更多信息,请参阅我在日期/时间文本转换的博客文章)。