2

我有以下代码:

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

4

2 回答 2

6
string newStr = string.Join(",", supportedImageFormats.Split(',')
                                     .Select(r => "*." + r));

输出:Console.WriteLine(newStr);

*.jpg,*.pdf,*.doc,*.docx,*.xlsx
于 2013-09-10T15:31:14.167 回答
1

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

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

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

于 2013-09-10T15:38:46.633 回答