34. Find files

The following extension method searches a directory for files that match a list of patterns:

// Find files that match any of the indicated patterns.
// Do not include duplicates and return the files sorted.
public static FileInfo[] GetFiles(this DirectoryInfo dirinfo,
IEnumerable<string> patterns,
SearchOption option = SearchOption.TopDirectoryOnly)
{
// Find files matching the patterns.
Dictionary<string, FileInfo> fileDict =
new Dictionary<string, FileInfo>()

foreach (string pattern in patterns)
{
foreach (FileInfo fileinfo in dirinfo.GetFiles(pattern,
option))
{
if (!fileDict.ContainsKey(fileinfo.FullName))
fileDict.Add(fileinfo.FullName, fileinfo);
}
}

// Sort and return.
FileInfo[] fileinfos = fileDict.Values.ToArray();
string[] filenames = fileDict.Keys.ToArray();
Array.Sort(filenames, fileinfos);
return fileinfos;
}

The method starts by making a dictionary to hold the files that it finds. Dictionaries are handy for quickly determining whether you have already found something that should be saved only once.

The code then loops through the patterns and calls the DirectoryInfo object's GetFiles method to find files that match each pattern. It loops through the returned files and adds those that have not already been found to the dictionary. This prevents the method from listing the same file twice case it matches more than one pattern.

After it finishes gathering the files, the code extracts the dictionary's values (the FileInfo objects) and keys (the filenames) into arrays. The items in a dictionary are not stored in any particular order, but its Values and Keys collections do return their contents in the same order, so corresponding items in the arrays go together.

The method sorts the FileInfo objects using the filenames as keys and returns the result.

The following method uses the GetFiles method to search for files that match patterns and that contain target text:

// Find files that match any of the indicated patterns and
// that contain the target string. Do not include duplicates
// and return the files sorted.
public static FileInfo[] FindFiles(this DirectoryInfo dirinfo,
IEnumerable<string> patterns, string target = "",
SearchOption option = SearchOption.TopDirectoryOnly)
{
// Find files matching the patterns.
FileInfo[] fileinfos = dirinfo.GetFiles(patterns, option);

// See if we should examine the files' contents.
if ((target != null) && (target.Length > 0))
{
// See which files contain the required contents.
List<FileInfo> newFiles = new List<FileInfo>();
foreach (FileInfo fileinfo in fileinfos)
{
string text = File.ReadAllText(fileinfo.FullName);
if (text.Contains(target)) newFiles.Add(fileinfo);
}
fileinfos = newFiles.ToArray();
}

return fileinfos;
}

This method calls the previous GetFiles method to get an array of FileInfo objects representing files that match the indicated patterns.

Then, if target is nonblank, the method loops through the files. For each file, the code uses File.ReadAllText to get the file's contents and uses IndexOf to see if the text contains the target string. If the file contains target, the code adds the file to its result list.

After it has checked every file, the method returns the files that it found.

The only remaining code of any real interest in this program is the following snippet, which converts patterns entered by the user into an array of pattern strings:

// Get the patterns.
string patternsString = patternsComboBox.Text;
if (patternsString.Contains(':'))
patternsString =
patternsString.Substring(
patternsString.IndexOf(':') + 1).Trim();
string[] patterns = patternsString.Trim().Split(
new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < patterns.Length; i++)
patterns[i] = patterns[i].Trim();

This code assumes that the pattern has a format similar to the following:

C# Files: *.cs; *.sln; *.resx; *.config

If the string contains a colon, the code takes only the characters following it, so it removes the C# Files: part of the preceding example. The code then uses the string class's Split method to separate the string at the semi-colon characters. It finishes by looping through the patterns and calling their Trim methods to remove whitespace from their ends.

The rest of the example solution is relatively straightforward. Download the FindFiles example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.187.223