Search code examples
c#linqsystem.io.directory

Linq Not Working on a List of Strings


I am trying to get list of strings containing file paths from a directory. User will be specifying file extensions in comma separated format such as "gif, jpg". This is my code.

private static List<string> GetFiles(string DirectoryPath, string Extensions)
        {
            List<string> FilePaths = new List<string>();

            if (Directory.Exists(DirectoryPath))
            {
                //Calling this line more than once is not allowed.
                List<string> AllFiles = Directory.EnumerateFiles(DirectoryPath, "*.*", SearchOption.AllDirectories).ToList();

                if (!string.IsNullOrEmpty(Extensions) && !string.IsNullOrWhiteSpace(Extensions))
                {
                    foreach (string Extension in Extensions.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        List<string> SearchedFiles = AllFiles.Where(f => f.EndsWith(Extension)).ToList();

                        FilePaths.AddRange(SearchedFiles);
                    }
                }
                else FilePaths.AddRange(AllFiles);
            }
            return FilePaths;
        }

The code works fine but it only retrieves results for the first extension and doesn't retrieves results for the next subsequent extensions. It simply ignores Linq specified in the first line inside foreach loop which initializes SearchedFiles equals a list with 0 results. I know it seems like the split function is not giving the subsequent extensions but it is working correctly. Also I've tried to specified extensions with . but didn't worked.

Note : I don't want to search inside directory multiple times.


Solution

  • You have an extra space at the start of your 2nd extension and whatever follows (index > 0).

    Simply trim that:

    f.EndsWith(Extension.Trim());