C#.Net:XML Document.Save抛出IOException

时间:2017-02-01 03:54:54

标签: c# xml

间歇性地,我在XMLDocument.Save()中看到了一个IO异常。最初,我认为它与以下链接中的问题相同: 1. XmlDocument.Save unhandled exception thrown from GC thread 2. Memory exception while XDocument.Save()

但是,我的调用栈与上面的线程中讨论的不同。这是我的调用堆栈: -------基本异常(从这里开始)--------- 根本原因可能是由于此异常:'System.IO.IOException' Message = IOException,

StackTrace=   at System.IO.__Error.WinIOError(Int32 errorCode, String str)
   at System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
   at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
   at System.IO.StreamWriter.Write(Char[] buffer)
   at System.IO.TextWriter.WriteLine()
   at System.Xml.XmlTextWriter.Indent(Boolean beforeEndElement)
   at System.Xml.XmlTextWriter.AutoComplete(Token token)
   at System.Xml.XmlTextWriter.WriteStartElement(String prefix, String localName, String ns)
   at System.Xml.XmlDOMTextWriter.WriteStartElement(String prefix, String localName, String ns)
   at System.Xml.XmlElement.WriteTo(XmlWriter w)
   at System.Xml.XmlElement.WriteContentTo(XmlWriter w)
   at System.Xml.XmlElement.WriteTo(XmlWriter w)
   at System.Xml.XmlElement.WriteContentTo(XmlWriter w)
   at System.Xml.XmlElement.WriteTo(XmlWriter w)
   at System.Xml.XmlDocument.WriteContentTo(XmlWriter xw)
   at System.Xml.XmlDocument.WriteTo(XmlWriter w)
   at System.Xml.XmlDocument.Save(String filename)

问题是我的IOException没有引用任何理由。 以下是代码:

XmlDocument traceXml = new XmlDocument();
traceXml.Load(traceFilename);
XmlElement root = t30Trace.DocumentElement;
XmlAttribute jobId = t30Trace.CreateAttribute("JobId");

jobId.Value = "45";
root.Attributes.Append(jobId);

traceXml.Save(traceFilename);

想要了解更多。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

Jon Skeet在回答类似问题时(请参阅https://stackoverflow.com/a/8354736/4151626),指出XmlDocument.Save()中可能存在一个错误,错误地将流固定。通过在XmlDocument.Save()方法之外直接控制流的创建和处理,我可以解决此暂停错误。

//e.g.
XmlWriter xw = new XmlWriter.Create(traceFilename);
traceXml.Save(xw);
xw.Close();
xw.Dispose();