【问题标题】:Looping over files of folder and add as attachment循环遍历文件夹的文件并添加为附件
【发布时间】:2014-11-12 17:57:42
【问题描述】:

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

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

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

【问题讨论】:

  • 循环通过Directory.GetFiles()寻找正确的扩展mail.Attachments.Add'ing每场比赛。

标签: c# .net smtp directory


【解决方案1】:

你可以试试这样的:

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

【讨论】:

    【解决方案2】:
    string[] fileNames  = System.IO.Directory.EnumerateFiles("C:\myLocation", "*.xls", System.IO.SearchOption.AllDirectories).ToArray();
    

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

    编辑:忘记 .ToArray()

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 1970-01-01
      • 2017-01-24
      • 2016-12-18
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多