2014-10-27 213 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