首页 > 解决方案 > 如何使用 (in) 一键 c# 在 listBox 中读取和搜索多个 txt 文件?

问题描述

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 包含来自目录和子文件夹的所有 .txt 文件...

现在我需要从此列表框中的所有文件并按一些字符串搜索。

我可以迭代循环并逐个文件读取文件吗?我不知道如何读取和搜索文件,需要先打开,然后将文件数据存储在某处,可能是列表或列表视图?

标签: c#io

解决方案


首先,我会使用它自己的一个类来存储您的搜索结果。当我们搜索文件时,如果我们找到了我们要搜索的关键字,我们将创建这个类的一个对象并将其添加到一个列表中。像这样的东西:

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;
}

推荐阅读