没必要总是添加一个附件

时间:2015-05-16 15:00:41

标签: c#

我的程序是一种类型的电子邮件,有时我想要插入附件,有时我不会。 因此,当我不想要插入附件显示错误

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;
    }
}

1 个答案:

答案 0 :(得分:0)

这应该可以解决您的错误!

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));  
}