尝试将一些数据从MemoryStream写入两个目标。首先,我将Xml对象写入内存流,然后从内存流写入Mail Attachment和Zip对象。尽管在每个步骤之间进行了Flush和Rewind,但只有第二个目标才能获取数据。我该如何解决这个问题?
这是我的来源:
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,我尝试先邮寄,然后拉链。现在一切正常。显然,Mail没有Flush功能,它实际上会延迟读取其字节......
答案 0 :(得分:-1)
尝试在第一个XmlPartWriter.Close()
之后调用Flush
。