属性 或索引器 "Attachments" 无法分配给 -- 它是只读的

Property or indexer "Attachments" cannot be assigned to -- it is read only

我正在尝试发送带有图片附件的邮件,但它仍然抛出错误 (*属性 或索引器 "Attachments" 无法分配给 -- 它是只读的 *)

string pathToPic = @"c:\MyDir\Img\img"+ automaticalyGeneratedNumber.toString() + ".png";


using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = Environment.MachineName,
                Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
                Attachments = new Attachment(@"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(@"c:\MyDir\Img") - 1).ToString() + ".png"),
            })
            {
                smtp.Send(message);
            }

为什么要把代码复杂化成那样。您需要使用 message.Attachments.Add,因为 Attachments 属性 是只读的:

var message = new MailMessage(fromAddress, toAddress)
{
    Subject = Environment.MachineName,
    Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
};
message.Attachments.Add(new Attachment(@"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(@"c:\MyDir\Img") - 1).ToString() + ".png"));
using (message)
{
    smtp.Send(message);
}