如何在C#中获取指定文件夹下所有对应扩展名文件并添加为邮件附件
问题:批量添加文件夹中的PDF/Word等文件为邮件附件
我有一段可正常运行的代码,能添加单个PDF作为邮件附件:
msg.Attachments.Add(new Attachment(Server.MapPath("~/myPdf/toAllInterns/IT_KFMC_Training_Plan_2023.pdf")));
我不想指定具体文件名,希望获取文件夹中所有PDF、Word或其他任意扩展名的文件,尝试用*.pdf替代文件名但报错。此前使用以下代码报错,期望能将所有PDF文件添加为附件:
msg.Attachments.Add(new Attachment(Server.MapPath("~/myPdf/toAllInterns/*.pdf")));
请问获取文件夹中所有对应文件并添加为附件的正确代码是什么?
解决方案
Attachment类的构造函数不支持通配符路径,必须先获取目标文件夹下的所有匹配文件,再逐个添加为附件。
1. 批量添加所有PDF文件
// 获取目标文件夹的物理路径 string folderPath = Server.MapPath("~/myPdf/toAllInterns/"); // 获取文件夹下所有PDF文件 string[] pdfFiles = Directory.GetFiles(folderPath, "*.pdf"); // 遍历每个文件,添加为附件 foreach (string filePath in pdfFiles) { msg.Attachments.Add(new Attachment(filePath)); }
2. 批量添加多种扩展名的文件(如PDF+Word)
如果需要同时添加PDF和Word格式的文件,可以指定多个搜索模式,合并结果后遍历添加:
string folderPath = Server.MapPath("~/myPdf/toAllInterns/"); // 定义需要匹配的文件扩展名 string[] searchPatterns = { "*.pdf", "*.docx", "*.doc" }; List<string> targetFiles = new List<string>(); // 收集所有符合条件的文件路径 foreach (string pattern in searchPatterns) { targetFiles.AddRange(Directory.GetFiles(folderPath, pattern)); } // 逐个将文件添加为邮件附件 foreach (string filePath in targetFiles) { msg.Attachments.Add(new Attachment(filePath)); }
注意事项
- 确保程序拥有目标文件夹的读取权限,避免触发权限异常。
- 若目标文件夹为空,代码会跳过附件添加逻辑,不会抛出错误。
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

