kat*_*tit 5 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;
}
Run Code Online (Sandbox Code Playgroud)
我只是采用我的数据库类型并转换为MailMessage.它被另一个函数发送.
代码分析告诉我,我没有处理正确的"msg".但是如果我在这里做的话 - 当我试图发送它时我会遇到异常.
此外,它抱怨没有在这里处理MemoryStream:
msg.Attachments.Add(new Attachment(new MemoryStream(attachment.Data),attachment.Name));
我不知道如何妥善处理它.我尝试了不同的东西,但在发送邮件说"流已关闭"时遇到异常
基本上你不应该 -稍后处理邮件消息将处理每个附件,这将处理每个流。此外,不处理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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我会说这有点过分了。