我正在try 编写C#代码来搜索文本文件中的特定字符串,并显示它是在哪一行找到的,或者如果找不到该字符串,则显示一条消息.我try 了几段不同的代码,但它们只有在找到字符串时才会执行某些操作.如果我放了一条Else语句来显示文本Not Found消息,如果找不到字符串,它就会忽略它.使用"While"循环结束时不执行任何操作,或者即使找到了字符串,它也会显示"未找到字符串"消息.我try 了循环和Foreach循环,但仍然没有得到我想要的结果.文本文件每行有一个单词.

以下是我拥有的代码:

public long CountLinesReader(string file)
{
  var lineCounter = 0L;
  using (StreamReader reader = new(file))
  {
    while (reader.ReadLine() != null)
    {
      lineCounter++;
    }
    return lineCounter;
  }
}

private void BtnSearch_Click(object sender, EventArgs e)
{
  StrSearchTerm = TxtSearchTerm.Text;
  StrTextFile = @Application.StartupPath + @"\TextFile.txt";
  IntLineCount = (int)CountLinesReader(StrTextFile);
  for(int i = 0; i < IntLineCount; i++) 
  {
    System.IO.StreamReader file = new System.IO.StreamReader(StrTextFile);
    while ((line = file.ReadLine()) != null)
    {
      StrLine = line;
      if(StrLine == StrSearchTerm)
      {
        LblSearch.Text = StrSearchTerm + " found on line: "+ i.ToString();
      }
    }
    if (StrLine == string.Empty)
    {
      LblSearch.Text = "The word: " + StrSearchTerm + " not found.";
    }
  }
}

推荐答案

使用以下方法查找出现搜索文本的行号.如果在文件中未找到搜索文本,则该方法返回一个空列表.

/// <summary>
/// Searches the specified file for a given word.
/// </summary>
/// <param name="filePath">Full path of the file.</param>
/// <param name="word">Search text.</param>
/// <returns>The line numbers of the occurences.</returns>
public List<int> SearchWord(string filePath, string word)
{
    var occurences = new List<int>();
    var lines = File.ReadAllLines(filePath);
    for (int i = 0; i < lines.Length; i++)
    {
        string currentLine = lines[i];
        if (currentLine.Contains(word))
        {
            occurences.Add(i + 1);
        }
    }
    return occurences;
}

要从Button次单击处理程序使用该方法,请执行以下操作:

private void BtnSearchFile_Click(object sender, EventArgs e)
{
    string filePath = @"D:\Test.txt";
    string word = TxtSearchTerm.Text;
    List<int> occurences = SearchWord(filePath, word);
    if (occurences.Any())
    {
        string lines = string.Join(",", occurences);
        string message = $"The word '{word}' occurs in lines {lines}";
        MessageBox.Show(message);
    }
    else
    {
        string message = $"The word '{word}' could not be found in the file.";
        MessageBox.Show(message);
    }
}

结果(找到时):

enter image description here

Csharp相关问答推荐

EF Core的GbContent如何 suppress 所有CS 8618(不可为空属性)警告?

循环访问Android视图中动态创建的子视图

Rx.Net -当关闭序列被触发时如何聚合消息并发出中间输出?

如何使用FastEndpoints和.NET 8 WebAppliationBuilder进行集成测试?

为什么.Equals(SS,StringComparison. ClientCultureIgnoreCase)在Net 4.8和6.0之间不同?

如何创建ASP.NET Core主机并在同一进程中运行请求

如何在Reflection. Emit中使用具有运行时定义的类型参数的泛型类型

在C#中使用类中的对象值

.NET 6控制台应用程序,RabbitMQ消费不工作时,它的程序文件中的S

持有者安全定义未显示在Swagger.NET 8中

C# CompareTo()和Compare()可以返回除-1和1以外的整数吗?

Swagger没有显示int?可以为空

在Docker容器中运行API项目时,无法本地浏览到index.html

Google OAuth令牌交换在.Net中不起作用

有条件地定义预处理器指令常量

为什么ReadOnlySpan;T&>没有Slice(...)的重载接受Range实例的?

用MongoDB c#驱动程序删除和返回嵌套数组中的文档

在平行内使用跨度.用于循环

如何在特定时间间隔运行多个后台任务?

如何阻止可传递依赖项出现在项目中