【问题标题】:Turn comma-separated string into GetFiles SearchPattern将逗号分隔的字符串转换为 GetFiles SearchPattern
【发布时间】:2013-09-10 15:28:02
【问题描述】:

我有以下代码:

private string[] FindExistingDocuments()
{
    string supportedImageFormats = "jpg,pdf,doc,docx,xlsx";

    DirectoryInfo documentPath = new DirectoryInfo("...");

    string supportedFileTypes = String.Join(",*.", supportedImageFormats.Split(','));
    string[] files = Directory.GetFiles(documentPath.FullName, supportedFileTypes, SearchOption.AllDirectories);

    return files;
}

作为搜索特定文件类型列表的一种方式,但当前代码的问题是String.Join 没有将分隔符放在第一项(这是有道理的)。

所以我的supportedFileTypes 原来是:

jpg,*.pdf,*.doc,*.docx,*.xlsx

但我希望它是:

*.jpg,*.pdf,*.doc,*.docx,*.xlsx

我可以用一种非常干净的方式制作这个吗?

注意:我无法更改supportedImageFormats的内容

【问题讨论】:

    标签: c# string join split getfiles


    【解决方案1】:
    string newStr = string.Join(",", supportedImageFormats.Split(',')
                                         .Select(r => "*." + r));
    

    输出:Console.WriteLine(newStr);

    *.jpg,*.pdf,*.doc,*.docx,*.xlsx
    

    【讨论】:

    【解决方案2】:

    我认识到@Habib 的答案很优雅,但也有一个非 LINQ 答案

     string newStr = "*." + string.Join(",*.", supportedImageFormats.Split(','));
    

    顺便说一句,所有这些都是没有意义的,因为你不能将那种模式传递给 Directory.GetFiles

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-18
      • 2018-08-16
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2012-09-04
      • 2013-02-04
      相关资源
      最近更新 更多