流作为System.Net.Mail的附件是0字节

问题描述:

我有一个项目,我正在使用PDF生成器将文件发送给用户。我们希望给用户提供将该文件附加到电子邮件的选项,而且我们无法将Stream对象和Attachment逻辑一起使用。

I've got a project where I'm using a PDF generator to send a file to a user. We'd like to give the user the option to attach this file to an email instead, and we're having trouble using the Stream object and Attachment logic together.

我们从ABCpdf开始,它有两种保存方式:它可以保存到Stream,或者如果给它一个字符串,它将尝试保存到磁盘上的文件。我们已经完成了两件事情。

We start with ABCpdf, which has two save methods: it can save to a Stream, or if you give it a string, it'll try to save to a file on the disk there. We've done both no problem.

Stream stream = new MemoryStream();
myPdf.Save(stream);

此刻一切都很酷 - stream 有几千字节的数据,如果.Save()到一个文件,你会得到一个具有相同字节数的实际文件。

Everything is mostly cool at this point - stream has several kilobytes of data, and if you .Save() to a file, you get an actual file with the same number of bytes.

所以我们附加到电子邮件此时(初始化邮件对象后,设置为:和从:等):

So we attach to an email at this point (after initializing the mail object, setting To: and From:, etc.):

mail.Attachments.Add(new Attachment(stream, "myPdf.pdf"));
mail.Send();

...这使我们能够接收到0个字节的电子邮件,但是正确的文件名。

...which gets us as far as receiving an email with 0 bytes, but the proper filename.

我在网上找到的所有示例都使用StreamReader或StreamWriter或Flush()或其他东西。它似乎总是比简单的传递一个Stream更复杂,但也许只有一两行更复杂。没有一个例子从Stream开始 - 他们总是试图将一个数组变成一个Stream,以显示你是多么容易,或从磁盘获取一个文件(我们不能做,这就是为什么我们很兴奋使用流)。

All the examples I'm finding online use a StreamReader or a StreamWriter or a Flush() or something. It always seems like it's more complicated than simply passing a Stream, but maybe only one or two lines more complicated. None of those examples start with a Stream - they're always trying to turn an array into a Stream to show you how easy that is, or grab a file from disk (which we can't do, which is why we're excited to use a Stream).

无论如何,如果有人可以解释我在做错什么或应该做什么,我真的很感激。谢谢。

Anyway, if anyone can explain what I'm doing wrong or what I ought to be doing, I'd really appreciate it. Thanks.

一个猜测...返回数据流到发送之前的开始

A guess... Back dat stream up to the beginning before sending nit

// Set the position to the beginning of the stream.
stream.Seek(0, SeekOrigin.Begin);
mail.Attachments.Add(new Attachment(stream, "myPdf.pdf"));
mail.Send();