Home > Enterprise >  DirectoryInfo.GetFiles with multiple filters
DirectoryInfo.GetFiles with multiple filters

Time:01-26

I am trying to get a list of FileInfo objects that satisfy multiple filters.

Every suggestion I have seen uses array of file names/paths instead of FileInfo:

var files = Directory.GetFiles(sLogPath, "*.*", SearchOption.TopDirectoryOnly)
            .Where(s => s.StartsWith("abc", StringComparison.CurrentCultureIgnoreCase) || s.StartsWith("def", StringComparison.CurrentCultureIgnoreCase));

What I am trying to get is:

DirectoryInfo di = new DirectoryInfo(sLogPath);
var files = di.GetFiles(<same filter as above>);

But it looks like I can only do something like:

var files = di.GetFiles("*_"   dateStr   ".log");
                

CodePudding user response:

Based on your comment to me on your question, it looks like you want to filter on file names, but get the FileInfos that correspond to these names.

You can do something like this

var di = new DirectoryInfo(sLogPath);

var files = di
    .GetFiles("*.*", SearchOption.TopDirectoryOnly)
    .Where(x => x.Name.StartsWith("abc", StringComparison.CurrentCultureIgnoreCase)
        || x.Name.StartsWith("def", StringComparison.CurrentCultureIgnoreCase))
    .ToList();

We're using the Name property in the filter and working with the FileInfo[] array returned by DirectoryInfo.GetFiles().

  • Related