代码分析抱怨我没有处理对象。这有什么不对?

时间:2011-08-19 17:32:58

标签: c# dispose code-analysis mailmessage

考虑这段代码

private MailMessage GetMailMessageFromMailItem(Data.SystemX.MailItem mailItem)
        {

            var msg = new MailMessage();

            foreach (var recipient in mailItem.MailRecipients)
            {
                var recipientX = Membership.GetUser(recipient.UserKey);
                if (recipientX == null)
                {
                    continue;
                }

                msg.To.Add(new MailAddress(recipientX.Email, recipientX.UserName));
            }

            msg.From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"],
                                   ConfigurationManager.AppSettings["EmailSenderName"]);

            msg.Subject = sender.UserName;
            if (!string.IsNullOrEmpty(alias)) msg.Subject += "(" + alias + ")";
            msg.Subject += " " + mailItem.Subject;
            msg.Body = mailItem.Body;
            msg.Body += Environment.NewLine + Environment.NewLine + "To reply via Web click link below:" + Environment.NewLine;
            msg.Body += ConfigurationManager.AppSettings["MailPagePath"] + "?AID=" + ContextManager.AccountId + "&RUN=" + sender.UserName;

            if (mailItem.MailAttachments != null)
            {
                foreach (var attachment in mailItem.MailAttachments)
                {
                    msg.Attachments.Add(new Attachment(new MemoryStream(attachment.Data), attachment.Name));
                }
            }

            return msg;
        }

我只是采用我的数据库类型并转换为MailMessage。 它被另一个函数发送。

代码分析告诉我,我没有处理正确的“msg”。但是如果我在这里做的话 - 当我试图发送它时我会遇到异常。

此外,它抱怨没有在这里处理MemoryStream:

  

msg.Attachments.Add(new Attachment(new MemoryStream(attachment.Data),   attachment.Name));

我不知道如何妥善处理它。我尝试了不同的东西,但在发送邮件说“流已关闭”时会遇到异常

3 个答案:

答案 0 :(得分:2)

基本上你不应该 - 稍后处理邮件消息将处理每个附件,这将处理每个流。此外,未处理未用于远程处理的MemoryStream将不会造成任何伤害。

我建议您取消此方法的警告。

编辑:我怀疑您可以使用[SuppressMessage]来取消该消息。


请注意,某些代码可能会在代码中途丢失代码,因此即使在调用代码中有using语句,也最终无法处理消息。如果你真的很烦,你可以写:

private MailMessage GetMailMessageFromMailItem(Data.SystemX.MailItem mailItem)
{
    bool success = false;
    var msg = new MailMessage();
    try
    {
        // Code to build up bits of the message
        success = true;
        return msg;
    }
    finally
    {
        if (!success)
        {
            msg.Dispose();
        }
    }
}

我个人认为这样做太过分了。

答案 1 :(得分:0)

关于“不处理”msg“”,我能想到的唯一方法是返回MailMessage,而不是传递对MailMessage的引用。 像这样的东西。不确定这是不是一个好主意。

private void GetMailMessageFromMailItem(ref MailMessage msg, Data.SystemX.MailItem mailItem)

答案 2 :(得分:-1)

一次性物品的创造者也应该处理它。如果您无法在此处置消息,则应将其从其他位置的创建者传入。在这种情况下,代码分析是正确的,如果忽略这些消息,最终可能会遇到非常不幸且难以调试的泄漏。