C# 不必总是添加附件

C# 不必总是添加附件,c#,C#,我的程序是一种电子邮件类型,有时我想插入附件,有时我不想。 所以当我不想插入附件时,会显示一个错误 Additional information: The 'fileName' parameter can not be an empty string. 这是我的程序代码 private void button4_Click(object sender, EventArgs e) { SmtpClient cliente = new SmtpClient(); Mai

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

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

为什么这两个按钮不同?为什么一次要附加两个附件?如果我想插入两个附件,请将它们插入2个文本框,否?或者存在另一个解决方案?为什么是两个?如果只想插入一个呢?一次插入两个似乎很奇怪-尤其是当你的问题涉及插入附件时。那么??如果我想插入两个附件,那么附上我所做的事情?如果你总是想插入两个附件,那很好-但是你的问题没有说明这一点。基本上,您的问题总体上是不清楚的-请阅读名称文件,msg不存在于当前上下文中:/@BrunoGonçalves这实际上是您的代码,带有一点if语句。如果它不起作用,那就回去学习一些c#i know the mens,但是字符串msg没有在这个按钮中声明,所以我需要声明?@BrunoGonçalves:你有
msg.Attachments。在你在问题中发布的代码中添加
,那么为什么它现在不起作用呢?我剪切了一些代码。。。SmtpClient客户端=新的SmtpClient();MailMessage msg=新的MailMessage();msg.Attachments.Add(新附件(anexostext.Text));msg.Attachments.Add(新附件(anexos2.Text));