Step-by-Step
Start a new project and arrange its form as shown in Figure 30-2.
Give the combo box the choices *.cs, *.txt, *.*, and any other patterns that you
think would be useful.
1. This is reasonably straightforward.
Give the form a
Load event handler that places the application’s startup path in the Directory
textbox (just to have somewhere to start).
1. Use code similar to the following:
// Start at the startup directory.
private void Form1_Load(object sender, EventArgs e)
{
directoryTextBox.Text = Application.StartupPath;
}
Give the Search button a
Click event handler that searches for the desired files.
1. Use code similar to the following:
// Search for les matching the pattern
// and containing the target string.
private void searchButton_Click(object sender, EventArgs e)
{
// Get the le pattern and target string.
string pattern = patternComboBox.Text;
string target = targetTextBox.Text.ToLower();
// Clear the result list.
leListBox.Items.Clear();
// Search for les.
DirectoryInfo dirinfo =
new DirectoryInfo(directoryTextBox.Text);
foreach (FileInfo leinfo in
dirinfo.GetFiles(pattern, SearchOption.AllDirectories))
{
// See if we need to look for target text.
if (target.Length > 0)
{
// If this le contains the target string,
// add it to the list.
string content =
File.ReadAllText(leinfo.FullName).ToLower();
if (content.Contains(target))
leListBox.Items.Add(leinfo);
}
else
596906c30.indd 357 4/7/10 12:34:27 PM