2016-02-26 110 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();