C#在不知道扩展名的情况下向mailmessage添加附件

时间:2013-06-26 10:19:59

标签: c# email smtp attachment mailmessage

系统生成具有不同扩展名的文件。 这些文件必须发送到电子邮件地址。

如何在不知道扩展名

的情况下将文件放入附件中

例如,必须将“sample.xls”添加到附件中,但应用程序也可以添加“sample.txt”,我该如何处理?我现在有

attachment = new System.Net.Mail.Attachment(@"M:/" + filename + ".xls");

我想要这样的东西

attachment = new System.Net.Mail.Attachment(@"M:/" + filename); // this didnt work

这样它就可以发送任何类型的文件。顺便说一句,文件名不是来自代码,而是来自没有任何扩展的数据库,所以简单的“样本”,它必须发送具有未知扩展名的文件,并且它必须在末尾发送带有正确扩展名的文件

非常感谢帮助!

2 个答案:

答案 0 :(得分:4)

也许这可以帮到你(如果你想通过循环来执行它):

string[] files = Directory.GetFiles("Directory of your file");
foreach (string s in files)
{
    if (s.Contains(@"FileName without extension"))
    {
        attachment = new System.Net.Mail.Attachment(s);
        mailMessage.Attachments.Add(attachment);   // mailMessage is the name of message you want to attach the attachment
    }
}

答案 1 :(得分:2)

假设filename仅为文件名且不包含其他路径组件:

foreach (string file in Directory.GetFiles(@"M:\", filename + ".*"))
{
   yourMailMessage.Attachments.Add(new System.Net.Mail.Attachment(file));
}

如果filename确实包含子目录,那么

string fullPath = Path.Combine(@"M:\", filename + ".*");
foreach (string file in Directory.GetFiles(Path.GetDirectoryName(fullPath), Path.GetFileName(fullPath)))
{
   yourMailMessage.Attachments.Add(new System.Net.Mail.Attachment(file));
}