2016-02-26 113 views
2

我在制作控制台应用程序,并且需要能够在文本文件中编写,搜索和删除条目,我可以将文件写入记事本文件,但基本上它是,这就是我要读文件:如何读取特定行的文件

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

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

这带来了文件中的所有文字,但我需要能够搜索到该文件中的具体数量,然后会弹出下三行在它下面。如何让它读取输入,使其与文本文件中的数字相匹配,然后显示接下来的3行?

回答

0

考虑你的问题和意见,回答,最后的答案是:

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!"); 
      } 

    } 
+0

什么当然你应该在阅读线路之前处理错误,因为输入的数字可能会超过行数 –

+0

@Ved如果答案为你工作,请接受它作为答案 –

+0

我试过它们,我不知道如何可以从中搜索到的数字该程序 被阅读。我将如何指定[linenumber]内的数字? – Ved

0

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

// 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();