C#将文本文件中的行添加到列表框中

时间:2012-08-26 20:06:35

标签: c#

我有一个包含文本行的文本文件,如果下一行符合条件,我试图将某些行添加到列表框中

如果行以#开头,那么如果下一行以@开头并且之后的所有行以@

开头,则添加该行
#add this line
@add this line
@add this line
@add this line
#dont add because the next line is not a @
#dont add because the next line is not a @
#dont add because the next line is not a @
#dont add because the next line is not a @
#add this line
@add this line
@add this line
#dont add because the next line is not a @
#add this line
@add this line  
#add this line
@add this line

希望这会让任何帮助都很棒

1 个答案:

答案 0 :(得分:3)

使用String的StartsWith方法http://msdn.microsoft.com/en-us/library/system.string.startswith.aspx

整个你的功能就像

var lines = File.ReadAllLines(yourpath);
var resultLines = new List<string>();
bool adding = false;
for(int i=0;i<lines.Length;i++)
{
    var line = lines[i];
    if((line.StartsWith("#") && i < lines.Length-1 && lines[i+1].StartsWith("@"))
       || adding && line.StartsWith("@"))
        adding = true;
    else if(i < lines.Length-1 && !lines[i+1].StartsWith("@"))
        adding = false;
    if(adding)
        resultLines.Add(line);
}