在文件夹的文件上循环并作为附件添加

本文关键字:添加 循环 文件夹 文件 | 更新日期: 2023-09-27 18:22:45

我有一个文件夹,其中将包含.pdf.xls,但数字会随时间变化,这是我的主要问题。现在,根据我的要求,我必须读取这两种类型的文件的位置,并将其作为附件添加到我的smtp邮件代码中,如下所示。。

Attachment att = new Attachment(sourceDir);
mail.Attachments.Add(att);

这是针对一个文件附件的。如何将上面描述的所有内容添加到此代码中作为附件。。请帮帮我。

在文件夹的文件上循环并作为附件添加

你可以试试这样的东西:

// Get all the files in the sourceDir
string[] filePaths = Directory.GetFiles(@"sourceDir");
// Get the files that their extension are either pdf of xls. 
var files = filePaths.Where(filePath => Path.GetExtension(filePath).Contains(".pdf") 
                                     || Path.GetExtension(filePath).Contains(".xls"));
// Loop through the files enumeration and attach each file in the mail.
foreach(var file in files)
{
    var attachment = new Attachment(file);
    mail.Attachments.Add(attachment);
}
string[] fileNames  = System.IO.Directory.EnumerateFiles("C:'myLocation", "*.xls", System.IO.SearchOption.AllDirectories).ToArray();

将在给定的目录中检索具有给定模式的文件名。您可以从源路径加载它们,并将它们附加到您的邮件中。

编辑:忘记了.ToArray()