使用XmlTextWriter时截断Stream的输出

时间:2014-06-28 09:23:53

标签: c#

 using (Stream responseStream = new MemoryStream())
                {
                    try
                    {
                        XmlTextWriter xmlWriter;
                        xmlWriter = new XmlTextWriter(@"D:\DEmo.txt", new UTF8Encoding(true));
                        xmlWriter.Formatting = Formatting.Indented;
                        xmlWriter.IndentChar = '\t';
                        xmlWriter.Indentation = 1;
                        xmlWriter.WriteStartDocument();
                        xmlWriter.WriteStartElement("D", "multistatus", "DAV:");
                        xmlWriter.WriteAttributeString("xmlns:M", "urn:schemas-microsoft-com:");
                        foreach (IWebDAVStoreItem item in store.Root.Items)
                        {
                            if (item is Server.Stores.DiskStore.WebDAVDiskStoreDocument)
                            {

                                ((Server.Stores.DiskStore.WebDAVDiskStoreDocument)item).AddProperties(xmlWriter);

                            }
                        }
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndDocument();

                        responseStream.Flush();

                        responseStream.Position = 0;
                        byte[] bytes = new byte[responseStream.Length];
                        responseStream.Read(bytes, 0, (int)responseStream.Length);
                        output = Encoding.ASCII.GetString(bytes); 
                        //output = (new StreamReader(responseStream)).ReadToEnd();
                        logger.Log(LogLevel.Warning, "\n" + output);
                        responseStream.Close();
                    }
                    catch(Exception ex) {
                        logger.Log(LogLevel.Warning, "\n" + ex.Message);
                    }
                }

我正在尝试从上面的代码生成XML,但是从MemoryStream读取并没有显示完整的XML.LML内容的最后部分总是被截断并不重要XML有多大。我无法想象发生了什么.Truncated输出看起来像这样。

     <?xml version="1.0" encoding="utf-8"?>
        <D:multistatus xmlns:M="urn:schemas-microsoft-com:" xmlns:D="DAV:">         
    <D:response>
            <D:href>/ANSI-ISO C++ Professional Programmers Handbook.pdf</D:href>
            <D:propstat>
                <D:status>HTTP/1.1 200 OK</D:status>
                <D:prop>        
<M:Win32CreationTime>2014-06-28T14:30:09</M:Win32CreationTime>
                    <M:Win32LastAccess>2014-06-28T14:30:09</M:Win32LastAccess>
                        <M:Win32LastModifiedTime>2014-06-28T14:30:09</M:Win32La

1 个答案:

答案 0 :(得分:5)

部分数据可能仍保留在XmlTextWriter的基础流缓冲区中。写完后,您应该调用XmlTextWriter的{​​{3}}方法。如果您想稍后继续写作,但仍希望确保所有数据都已写入,则可以使用Close