문제

Trying to serialize an XmlDocument to file. The XmlDocument is rather large; however, in the debugger I can see that the InnerXml property has all of the XML blob in it -- it's not truncated there.

Here's the code that writes my XmlDocument object to file:

// Write that string to a file.
var fileStream = new FileStream("AdditionalData.xml", FileMode.OpenOrCreate, FileAccess.Write);
xmlDocument.WriteTo(new XmlTextWriter(fileStream, Encoding.UTF8) {Formatting = Formatting.Indented});
fileStream.Close();

The file that's produced here only writes out to line like 5,760 -- it's actually truncated in the middle of a tag!

Anyone have any ideas why this would truncate here?

Update: I found the source of the issue. I was not closing the XML Text Writer before closing the file stream! D'oh!

도움이 되었습니까?

해결책

The XmlTextWriter wasn't closed properly. Woops!

다른 팁

You can try to Flush the stream before closing. If AutoFlush is true, I think it gets flushed on Close() anyway, but it might be worth a shot:

// Write that string to a file. 
var fileStream = new FileStream("AdditionalData.xml", FileMode.OpenOrCreate, FileAccess.Write); 
xmlDocument.WriteTo(new XmlTextWriter(fileStream, Encoding.UTF8) {Formatting = Formatting.Indented}); 
fileStream.Flush();
fileStream.Close(); 

It's way way way... after the original question was asked, but it showed up on Google results.

I went through something similar today and wanted to share my answer (for the next unfortunate soul who faces this confusion).

I'm using a StreamWriter (sw) with a MemoryStream (ms) to keep data in memory and then flush out to a filestream (fs) at certain intervals.

So I was doing

    sw.WriteLine(DateTime.Now.ToString("u").Replace("Z", "") & ":  " & entry)

And then after all was said and done

    ms.WriteTo(fs)
    fs.Flush()
    fs.Close()
    ms.Close()

Problem was that I wasn't flushing the StreamWriter to the MemoryStream first

Altering to this resolved my issue.

    sw.Flush()
    ms.WriteTo(fs)
    fs.Flush()
    fs.Close()
    ms.Close()

I faced this issue today when the code was as below:

XmlTextWriter writer = new XmlTextWriter("IdP.xml", null);
writer.Formatting = Formatting.Indented;
xmlElement.WriteTo(writer);

The issue was fixed when I changed it as below:

using (XmlTextWriter writer = new XmlTextWriter("IdP.xml", null))
{
    writer.Formatting = Formatting.Indented;
    xmlElement.WriteTo(writer);
}

Hope this is useful to someone.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top