在给定字符串后读取文件中的行并将每行存储在变量中

时间:2016-12-15 23:23:51

标签: c#

我有一个文本文件,我想读取本文中特定字符串后面的每一行,并将每一行存储在一个变量中。

文本格式为:

[15-06-1999]
Brian
John
186

[26-08-2000]
//...

如何从空白行下方[15-06-1999]阅读并将 3个字符串存储在单独的变量中?

我还没有找到任何高效方法。

我正在尝试在C#中执行此操作。

2 个答案:

答案 0 :(得分:2)

我不能说这是更有效因为我不知道你的方式(顺便说一句:你真的有一个工作吗?)..但至少,这有效....

var date = "[15-06-1999]";
var lines = File.ReadLines(filename)
            .SkipWhile(line => line != date)
            .Skip(1) //skip date 
            .TakeWhile(line => !string.IsNullOrEmpty(line))
            .ToList();

答案 1 :(得分:1)

var path = "path to your text file";
string[] lines = File.ReadAllLines( path );
int lineNumber = 0;
for( int i = 0; i < lines.Length; i++ ) 
{
   if( lines[i] == "[15-06-1999]" ) 
   {
      lineNumber = i;
      break;
   }
}

for( int i = lineNumber + 1; i < lines.Length; i++ ) 
{
   // These lines are after the line with [15-06-1999] do whatever you want here
}

确保通过将其置于顶部来导入命名空间:using System.IO;

这是另一种方法(更好),它会在请求行时读取行而不是读取整个文件。感谢pm100的建议。

var path = "path to your text file";
IEnumerable<string> lines = File.ReadLines( path );
bool lineFound = false;
foreach( var thisLine in lines ) 
{
   if( lineFound ) 
   {
      // These lines are after the line with [15-06-1999] do whatever you want here
   }
   else if( thisLine == "[15-06-1999]" ) 
   {
      lineFound = true;
   }
}
相关问题