没有必要总是添加附件

本文关键字:添加 | 更新日期: 2023-09-27 17:49:27

我的程序是一个类型的电子邮件,有时我想插入附件,其他时间我不。所以当我不想插入附件时显示错误

Additional information: The 'fileName' parameter can not be an empty string.

这是我的程序的代码。

private void button4_Click(object sender, EventArgs e)
{       SmtpClient cliente = new SmtpClient();
        MailMessage msg = new MailMessage();
    msg.Attachments.Add(new Attachment(Anexostxt.Text));
    msg.Attachments.Add(new Attachment(anexos2.Text));  
}
private void button6_Click(object sender, EventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    if(dlg.ShowDialog()==DialogResult.OK)
    {
        string picpath = dlg.FileName.ToString();
        Anexostxt.Text = picpath;
    }
}

没有必要总是添加附件

这应该可以修复您的错误!

private void button4_Click(object sender, EventArgs e)
{   
    if(!String.IsNullOrEmpty(Anexostxt.Text) && File.Exists(Anexostxt.Text))    
        msg.Attachments.Add(new Attachment(Anexostxt.Text));
    if(!String.IsNullOrEmpty(anexos2.Text) && File.Exists(anexos2.Text)) 
        msg.Attachments.Add(new Attachment(anexos2.Text));  
}