I was browsing at DevPinoy.org today when I saw this interesting post by n@rds about searching for files in a directory using multiple search patterns and it made me realize that there are alot of ways you can accomplish this task. Here are some examples on how you can search files in a directory using multiple search patterns
The For-Each way
/// <summary>
/// Get all the files in a directory that match
/// the specified search pattern
/// </summary>
/// <param name="path">The directory to seach</param>
/// <param name="listOfSearchPatterns">the list of search patterns</param>
/// <returns>The list of files that match the specified pattern</returns>
public static List<string> GetFiles(string path
, List<string> listOfSearchPatterns)
{
List<string> matchingFiles = new List<string>();
foreach (string pattern in listOfSearchPatterns)
{
//add the the files that match our pattern to our list
matchingFiles.AddRange(Directory.GetFiles(path, pattern));
}
return matchingFiles;
}
The List.ForEach style
/// <summary>
/// Demostrates how to get files using List.ForEach method
/// </summary>
/// <param name="path">The directory to seach</param>
/// <param name="listOfSearchPatterns">the list of search patterns</param>
/// <returns>The list of files that match the specified pattern</returns>
public static List<string> GetFilesUsingListForEach(string path
, List<string> listOfSearchPatterns)
{
List<string> matchingFiles = new List<string>();
listOfSearchPatterns.ForEach(
delegate(string s)
{
matchingFiles.AddRange( Directory.GetFiles(path, s) );
});
return matchingFiles;
}
The LINQ approach
/// <summary>
/// Demostrates how to get files using LINQ
/// </summary>
/// <param name="path">The directory to seach</param>
/// <param name="listOfSearchPatterns">the list of search patterns</param>
/// <returns>The list of files that match the specified pattern</returns>
public static List<string> GetFilesUsingLINQ(string path
, List<string> listOfSearchPatterns)
{
List<string> matchingFiles = new List<string>();
foreach (string s in listOfSearchPatterns)
{
var files = from f in Directory.GetFiles(path,s)
select f;
//add the files to our list
matchingFiles.AddRange(files);
}
return matchingFiles;
}
Now if you want to delete files that match a search pattern all you need to do is:
/// <summary>
/// Delete all files in a directory that match
/// the specified search pattern
/// </summary>
/// <param name="path">The directory to seach</param>
/// <param name="listOfSearchPatterns">the list of search patterns</param>
public static void DeleteFiles(string path
, List<string> listOfSearchPatterns)
{
List<string> matchingFiles = new List<string>();
//get the files to delete
matchingFiles = GetFiles(path, listOfSearchPatterns);
//iterate thru each item in our list
foreach (string fileToDelete in matchingFiles)
{
//delete the file
File.Delete(fileToDelete);
}
}
Cool huh? How about you? what's your approach?
Posted
Feb 01 2008, 05:00 PM
by
keithrull