private void btnOpen_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
string[] allfiles = Directory.GetFiles(fbd.SelectedPath, "*.txt*",
SearchOption.AllDirectories);
foreach (string file in allfiles)
{
FileInfo info = new FileInfo(file);
listBox1.Items.Add(Path.GetFileName(file));
}
}
}
有一个listbox1,其中包含来自direcory和子文件夹的所有.txt文件...
现在,我需要从该列表框中选择所有文件并按字符串进行搜索。
我可以迭代循环并逐文件读取文件吗? 我不知道如何读取和搜索文件,需要先打开文件,然后将文件数据存储在某个地方,例如list或listView吗?
答案 0 :(得分:0)
首先,我将使用其自己的类来存储您的搜索结果。当我们搜索文件时,如果找到要搜索的关键字,则将创建此类的对象并将其创建到列表中。像这样:
public class SearchResults
{
public string FilePath { get; set; }
public string SearchWord { get; set; }
public int Occurences { get; set; }
}
然后,您可以使用System.IO.File
类来读取文件。请记住,这不是唯一的方法,而只是这样做的一种方法。这里有一个文件名列表,它等效于程序中的数组。
var searchTerm = "Hello";
var fileList = new List<string>() { "A.txt", "B.txt", "C.txt" };
var resultList = new List<SearchResults>();
// Iterate through files. You already are doing this.
foreach (var file in fileList)
{
// Check to see if file exists. This is a second line of defense in error checking, not really necessary but good to have.
if (File.Exists(file))
{
// Read all lines in the file into an array of strings.
var lines = File.ReadAllLines(file);
// In this file, extract the lines contain the keyword
var foundLines = lines.Where(x => x.Contains(searchTerm));
if (foundLines.Count() > 0)
{
var count = 0;
// Iterate each line that contains the keyword at least once to see how many times the word appear in each line
foreach (var line in foundLines)
{
// The CountSubstring helper method counts the number of occurrences of a string in a string.
var occurences = CountSubstring(line, searchTerm);
count += occurences;
}
// Add the result to the result list.
resultList.Add(new SearchResults() { FilePath = file, Occurences = count, SearchWord = searchTerm });
}
}
}
CountSubstring()
辅助方法。
public static int CountSubstring(string text, string value)
{
int count = 0, minIndex = text.IndexOf(value, 0);
while (minIndex != -1)
{
minIndex = text.IndexOf(value, minIndex + value.Length);
count++;
}
return count;
}