【问题标题】:How do I read a file for a specific line如何读取特定行的文件
【发布时间】:2016-02-26 19:00:22
【问题描述】:

我正在制作一个控制台应用程序,我需要能够在文本文件中写入、搜索和删除条目,我可以将文件写入记事本文件,但基本上就是这样,这就是我必须阅读的文件:

public static void SearchDetails()
{
Console.WriteLine("Enter ID Number");

string myfile = System.IO.File.ReadAllText(@"C:\\file.txt");
System.Console.WriteLine(myfile);
}

这会调出文件中的所有文本,但我需要能够在文件中搜索特定数字,然后调出下面的三行。如何让它读取输入,使其与文本文件中的数字匹配,然后调出接下来的 3 行?

【问题讨论】:

    标签: c# io console-application


    【解决方案1】:

    所以你可以对结果做任何你想做的事情,但这样的事情就是你想要的

    // Read the file and display next three lines
    System.IO.StreamReader file = new System.IO.StreamReader("c:\\file.txt");
    
    string line;
    int lineCnt = 3;
    while((line = file.ReadLine()) != null)
    {
        if (line.Contains(myID) & !bGet) 
        {
            bool bGet = true;
        }
    
        if (bGet && lineCnt > 0) 
        {
            bool bGet = true;
            Console.WriteLine (line);
            lineCnt--;
        }
    
        if(lineCnt == 0) {break;}
    
    }
    file.Close();
    
    // Suspend the screen.
    Console.ReadLine();
    

    【讨论】:

      【解决方案2】:

      考虑到你的问题和需要回答的问题,最终的答案是:

          public static void SearchDetails()
          {
          Console.WriteLine("Enter ID Number");
          int Id = 0;
          int.TryParse(Console.ReadLine(), out Id);
       string[] lines = System.IO.File.ReadAllLines(@"C:\\file.txt");
                  List<string> IdLines = lines.Where((x, i) => i % 4 == 0).ToList();
                  int IdLine = IdLines.IndexOf(Id);
                  if (IdLine != -1)
                  { //then result found
                      //Id is what user searched for or
                     // string Id = lines[IdLine*4];
                      //string[] results = lines.Where((x, i) => i > IdLine * 4 && i < IdLine * 4 + 4).ToArray();
                 for(int i=IdLine*4;i<IdLine*4+4;i++)
                  System.Console.WriteLine(lines[i]);
                  }
                  else
                  {
                      Console.WriteLine("no results!");
                  } 
      
          }
      

      【讨论】:

      • 当然你应该在读取行之前处理错误,因为输入的数字可能超过行数
      • @Ved 如果答案对你有用,请接受它作为答案
      • 我试过了,但我不确定如何才能读取从程序中搜索到的号码。我将如何指定 [linenumber] 中的数字?
      • 感谢您的回复,这绝对让我更接近我需要做的事情,但我正在努力的主要事情是能够找到与搜索的号码匹配的内容,例如搜索 2 会带来增加 ID 2 以及下面的 3 行,而不仅仅是行号,知道怎么做吗?
      • @Ved 下面三行是什么意思?你的意思是所有的第0、1、2行?我没明白你的意思
      猜你喜欢
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 2023-03-08
      • 2022-11-20
      相关资源
      最近更新 更多