2014-10-27 208 views
0

我有一個包含用戶記錄的文本文件。在文本文件中,一行用戶記錄存在於三行文本文件中。現在根據我的要求,我必須讀取前三行用於一個用戶,過程,並插入到數據庫和下三行用於第二用戶等等..如何從c中的文本文件讀取多行文件#

這裏是我已經用於單線從文本文件讀出的代碼..

 if (System.IO.File.Exists(location) == true) 
     { 
      using (StreamReader reader = new StreamReader(location)) 
      { 
       while ((line = reader.ReadLine()) != null) 
       {  
         line = line.Trim(); 
       } 
     } 
     } 

請幫助我閱讀多行,在這種情況下,從文本文件中的3行。

謝謝..

+4

使用循環計數器和模3條件同時 – Paul 2014-10-27 10:46:28

回答

1

你可以這樣做:

if (System.IO.File.Exists(location) == true) 
     { 
      var lines=File.ReadAllLines(location); 
      int usersNumber = lines.Count()/3; 
      for(int i=0; i < usersNumber; i++){ 
       var firstField=lines[i*3]; 
       var secondField=lines[i*3 +1]; 
       var thirdField=lines[i*3 +2]; 
       DoStuffs(firstField,secondField,thirdField); 
      } 
      if(lines.Count() > usersNumber *3) //In case there'd be spare lines left 
       DoSomethingElseFrom(lines, index=(usersNumber*3 +1)); 
     } 

你正在閱讀您的文件的所有行,計數有多少用戶有(3組),然後爲每個組你」重新檢索其關聯信息,並最終處理與同一用戶相關的3個字段的組。

+1

你可以爲負投票的理由加入3條線?這會更有建設性,因爲我可以嘗試改進答案。 – 2014-10-27 10:55:28

+0

我沒有低估這一點,但首先想到這將有點工作(原則上),但需要一些驗證,因爲線數不足。 – Adrian 2014-10-27 10:56:16

+0

這些線條究竟能達到多少?在進入循環之前檢查行數。 – 2014-10-27 10:58:09

1

我已經使用了虛擬dource文件與此內容:

line1_1 /*First line*/ 
line1_2 
line1_3 
line2_1 /*second line*/ 
line2_2 
line2_3 
line3_1 /*third line*/ 
line3_2 
line3_3 
line4_1 /*fourth line*/ 
line4_2 
line4_3 

string result = String.Empty; 
string location = @"c:\users\asdsad\desktop\lines.txt"; 
if (System.IO.File.Exists(location) == true) 
    { 
     using (StreamReader reader = new StreamReader(location)) 
     { 
      string line = String.Empty; 
      while ((line = reader.ReadLine()) != null) /*line has the first line in it*/ 
      { 
       for(int i = 0; i<2; i++) /*only iterate to 2 because we need only the next 2 lines*/ 
        line += reader.ReadLine(); /*use StringBuilder if you like*/ 
       result += line; 
      } 
    } 
    result.Dump(); /*LinqPad Only*/ 
+0

確定了..但在我的要求中,我必須獲得三行字符串,而不是像字符串List Collection那樣在您的解決方案中。如何實現此目的? – 2014-10-27 11:08:17

+0

你的意思是像line1 + line2 + line3? – Marco 2014-10-27 11:10:39

+0

是的!以字符串格式 – 2014-10-27 11:13:14

0
void Main() 
{ 
    var location = @"D:\text.txt"; 
    if (System.IO.File.Exists(location) == true) 
    { 
     using (StreamReader reader = new StreamReader(location)) 
     { 
      const int linesToRead = 3; 
      while(!reader.EndOfStream) 
      { 
       string[] currReadLines = new string[linesToRead]; 
       for (var i = 0; i < linesToRead; i++) 
       { 
        var currLine = reader.ReadLine(); 
        if (currLine == null) 
         break; 

        currReadLines[i] = currLine; 
       } 

       //Do your work with the three lines here 
       //Note; Partial records will be persisted 
       //var userName = currReadLines[0] ... etc... 
      } 
     } 
    } 
} 
+0

你能告訴我如何讀取字符串而不是字符串數組嗎?我只需要字符串? – 2014-10-27 11:26:50