2016-08-30 31 views
0

试图将MemoryStream中的某些数据写入两个目标。首先,我将一个Xml对象写入内存流,然后从内存流写入一个Mail Attachment和一个Zip对象。尽管在每个步骤之间进行了Flush和倒带,但只有第二个目标获取数据。我该如何解决?Stream Flush无效,将MemoryStream写入两个目标

这里是我的源:

using (Stream XmlPartStream = new MemoryStream()) 
using (XmlTextWriter XmlPartWriter = new XmlTextWriter(XmlPartStream, Encoding.Unicode)) 
{ 
    XDocument TheXInvoice = TheInvoice.XInvoice(dtInvoiceLines); 
    XmlPartWriter.Formatting = Formatting.Indented;//xml output will be pretty-printed 
    TheXInvoice.WriteTo(XmlPartWriter);//write to the MemoryStream 
    XmlPartWriter.Flush();//finish writing to MemoryStream 

    XmlPartStream.Seek(0, SeekOrigin.Begin);//rewind stream (Position=0 would also work) 
    Attachment XmlPart = new Attachment(XmlPartStream, InvoiceXmlName, "application/xml"); 
    TheMail.Attachments.Add(XmlPart); 
    XmlPartStream.Flush();//finish writing from MemoryStream to Attachment 
    // BUG: no bytes in the Attachment 

    XmlPartStream.Seek(0, SeekOrigin.Begin);//rewind stream (Position=0 would also work) 
    byte[] ZippedXml = LempelZiv.GZip(XmlPartStream); 
    // OK: Entire XML in the ZippedXml 

更新:

由于评论者rinukkusu,我想第一个邮件,然后压缩。现在它可以正常工作。显然,邮件缺乏Flush功能,并且它延迟实际读取其字节...

+1

可能只有在您实际发送邮件时才会读取附件中的流,因此光标在压缩后会再次结束。 – rinukkusu

+0

这是一件疯狂的事情,但之前它对我有用。尝试在Flush之前或之后添加System.Threading.Thread.Sleep(2500)。我不记得细节,但我以前使用过这个,就好像系统需要一点时间才能赶上。当然,这更可能是@rinukkusu是对的:) – Missy

+0

我面临同样的问题,不得不创建一个新的内存流 – Akanksha

回答

-1

尝试调用XmlPartWriter.Close()后第一个Flush

+0

这也会关闭底层的流,所以在这之后它不能被读取。这将如何帮助? – rinukkusu

+0

这可能确实会迫使Mail快速阅读数据,但正如downvoters指出的那样,也会阻止再次从该流中读取数据,迫使我在阅读邮件之前进行zip阅读。谢谢你的努力。 – Roland

相关问题