在C#中我设计了一个应用程序,通过它我可以从桌面发送电子邮件......
我也可以发送带附件的电子邮件.....
但是当我尝试发送没有附件的邮件时,它会给出错误参数FileName 不能是一个空字符串。参数名称:filename
所以请告诉我如何删除此错误
private void send_Click(object sender, EventArgs e)
{
try
{
SmtpClient client = new SmtpClient("smtp.live.com", 25);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("xxxx@hotmail.com", "zzzz");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("xxxx@hotmail.com");
msg.To.Add(textBox1.Text);
msg.Subject = textBox2.Text;
msg.Attachments.Add(new Attachment(textBox3.Text.ToString()));
msg.Body = textBox4.Text;
client.Send(msg);
MessageBox.Show("Done");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void browse_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox3.Text = dlg.FileName.ToString();
}
}
答案 0 :(得分:1)
更改此行:
msg.Attachments.Add(new Attachment(textBox3.Text.ToString()));
为:
if(!string.IsNullOrEmpty(textBox3.Text.ToString()))
msg.Attachments.Add(new Attachment(textBox3.Text.ToString()));
new Attachment(textBox3.Text.ToString())
部分给出了这个错误。当你没有在textBox3
中输入任何路径时,它是空的,但是在Attachment
构造函数中,它仍然试图让文件驻留在该路径上,当它找不到该文件时,它会给你那个例外。只需不调用Attachment
构造函数就可以避免问题。
答案 1 :(得分:0)
检查字符串是否为空
if(!string.IsNullOrEmpty(textBox3.Text.ToString()))
{
msg.Attachments.Add(new Attachment(textBox3.Text.ToString()));
}