2

I have the following code:

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

Which functions as a way of searching for a specific list of file types but the problem with the current code is that String.Join does not put the separator at the first item (which makes sense).

So my supportedFileTypes turns out to be:

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

But I want it to be:

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

Can I somehow make this in a pretty clean way?

Note: I cannot alter the contents of supportedImageFormats

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dumpen
  • 1,622
  • 6
  • 22
  • 36

2 Answers2

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

Output: Console.WriteLine(newStr);

*.jpg,*.pdf,*.doc,*.docx,*.xlsx
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 1
    Thank you for the answer. I just realised GetFiles does not support multiple extensions so I had to use this http://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters :( – Dumpen Sep 10 '13 at 15:45
1

I recognize the elegance of the answer from @Habib, but there is also a non LINQ answer

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

By the way, all of this is pointless because you can't pass that kind of pattern to Directory.GetFiles

Steve
  • 213,761
  • 22
  • 232
  • 286