Josh
Josh

Reputation: 5

How to search for Files using GetFiles method (multiple criteria..)

The code below obviously searches a directory for Files that contain the word "FINAL" but what I'm wondering is can I add to its search criteria? I have a Well_Name and Actual_Date strings that I would like to search for in the File names in addition to the "FINAL" word. Thoughts? Thanks in advance.

DirectoryInfo myDir = new DirectoryInfo("C://DWGs");
var files = myDir.GetFiles("FINAL");

//Can I do something like this to add to my search criteria?
var files = myDir.GetFiles("FINAL" + 
                            drow["Well_Name"].ToString() + 
                            drow["Actual_Date"]);

Upvotes: 0

Views: 2143

Answers (2)

Yuriy
Yuriy

Reputation: 11

GetFiles method does not support multiple search criteria, but there is a simple way around this limitation. Run a getFile for each file extension, and then "merge" returned arrays into a List<>. Then use a List's ToArray method to "convert" a List back to an Array. I used this approach, and it works for me The code is below (do not forget to reference "using System.Collections.Generic;" namespace):

// Get the DirectoryInfo and FileInfo objects for aspx and html files.
FileInfo[] files_aspx = dir.GetFiles("*.aspx");
FileInfo[] files_html = dir.GetFiles("*.html");

List<FileInfo> files = new List<FileInfo>();
files.AddRange(files_aspx);
files.AddRange(files_html);
files.ToArray();

Upvotes: 1

msarchet
msarchet

Reputation: 15242

var files = myDir.GetFileInfo()
                 .Where(f => f.FileName.Contains("FINAL") ||
                             f.FileName.Contains(drow["Well_Name"].ToString()) ||
                             f.FileName.Contains(drow["Actual_Date"]));

Since GetFiles() returns an Enumerable Collection of FileInfo you can just check all of the file names for the criteria that you want.

If you want to get really generic on this you could write a function that looks like this

public IEnumerable<FileInfo> addCriteria(IEnumerable<FileInfo> FileList,
                                         List<String> searchCriteria)
{ 
   var newFileList = FileList;
   foreach(String criteria in searchCriteria)
   {
       newFileList = newFileList.Where(f => f.FileName.Contains(criteria).AsQueryable();
   }
   return newFileList.AsEnumerable();
}

Upvotes: 3

Related Questions