通过StreamReader搜索字符串

时间:2018-06-03 22:51:11

标签: c#

我在C#中使用此代码从.txt文件执行字符串搜索,但它只显示一行。

我在第一场比赛中需要3分。

示例:搜索:1

结果

第1行

第2行

第3行

请帮帮我。问候 .......................................

文字档案

代码:1

注意名称:Josh

body注意:tex

代码:2

注意名称:Josh

正文注释:txt

C#代码

using System;
using System.IO;
class Test 
{
  public static void Main() 
  {
    enter code here
    try 
    {
      string searchString = "some string";
      searchString = Console.ReadLine();
      // Create an instance of StreamReader to read from a file.
      // The using statement also closes the StreamReader.
      using (StreamReader sr = new StreamReader("TestFile.txt")) 
      {
        string line;
        // Read and display lines from the file until the end of 
        // the file is reached.
        while ((line = sr.ReadLine()) != null) 
        {
          if(line.Contains(searchString))
          {
            // Do some logic (the search string is found)
              //   I need to show 3 lines here
              //    Code:1
              //   Note name: Josh
              //   Body Note : tex
              // for the moment Console.WriteLine(line);just shows me 1               

                  Console.WriteLine(line);
                  count++;
          }
        }
      }
    }
    catch (Exception e) 
    {
      // Let the user know what went wrong.
      Console.WriteLine("The file could not be read:");
      Console.WriteLine(e.Message);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您只获得一行的原因是,一旦找到匹配项,您将继续将searchString与文件中的每一行进行比较。您可以添加一个标记来绕过contains,如:

bool found = false;
using (StreamReader sr = new StreamReader("TestFile.txt")) 
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        // bypass the search once we've found a match
        if(found || line.Contains(searchString))
        {
            // Do some logic (the search string is found)
            //   I need to show 3 lines here
            //    Code:1
            //   Note name: Josh
            //   Body Note : tex
            // for the moment Console.WriteLine(line);just shows me 1               
            found = true;
            Console.WriteLine(line);
            count++;
            if(count == 3) {
                break;
            }
        }
    }
}

或者您可以一直阅读stream,然后检查并进行后处理:

using (StreamReader sr = new StreamReader("TestFile.txt"))
{
    string contents = sr.ReadToEnd();
    if (contents.Contains(searchString))
    {
        // do you magic here
    }
}