Question

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

Was it helpful?

Solution

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

Output: Console.WriteLine(newStr);

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top