将附件添加到MailMessage时流关闭错误 [英] Stream closed error when adding attachment to MailMessage

查看:139
本文介绍了将附件添加到MailMessage时流关闭错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码将文件附加到电子邮件中。

I use the following code to attach a file to an email message.

msg = new MailMessage();

    using (strMem = new MemoryStream((byte[])attDr["filedata"]))
    {
        using (strWriter = new StreamWriter(strMem))
        {
            strWriter.Flush(); strMem.Position = 0;
            using (attachment = new Attachment(strMem, attDr["filename"].ToString()))
            {
                msg.Attachments.Add(attachment);
            }
        }
    }

...
...
msg.Send();  //Error: System.ObjectDisposedException: Cannot access a closed Stream.

错误消息是://错误:System.ObjectDisposedException:无法访问关闭的流

The error message is: //Error: System.ObjectDisposedException: Cannot access a closed Stream

我猜测退出块时, USING语句将关闭流。但是,为什么 Attacments.Add()不制作自己的流副本?

Im guessing that the "USING" statement closes the stream when exiting the block. But why doesnt "Attacments.Add()" make its own copy of the stream?

推荐答案

Send()方法在进行中访问附件以将其嵌入到邮件中。在这里,内存流被丢弃了。您需要在 using 语句内移动Send()调用,以使流在消息发送后之后才被处理掉。

The Send() method is going to access the attachments to embed them into the mail message. That goes kaboom here, the memory stream was disposed. You need to move the Send() call inside of the using statements so the stream doesn't get disposed until after the message is sent.

这里不需要提及使用,因为内存流中没有任何需要处置的非托管资源,这总是让我陷入困境。所以我不会提出。

Mentioning that using isn't necessary here because a memory stream doesn't have any unmanaged resources that need to be disposed always gets me into trouble at SO. So I won't bring that up.

这篇关于将附件添加到MailMessage时流关闭错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆