读取文本文件中某一行之后的行(c sharp)
本文关键字:一行 sharp 之后 取文本 文件 读取 | 更新日期: 2023-09-27 18:27:43
假设我有一个包含以下信息的文本文件:
嘿
所有
这个
是
我的
问题
我想做的只是包含"this"的行是"&"我的",我不知道它们离顶部有多远,也不知道它们到底有多远,我只知道它们是按这个顺序排列的,它们周围的行包含"all"answers"question"。我已经使用了while循环来处理"问题"之前的所有内容,但我不知道如何指示它应该忽略"这个"之前的一切(不包括它)。你能帮我吗?
"最简单"的方法是将文件的行转换为列表,并使用通用的收集方法来执行您想要的操作。
List<string> AllLines = File.ReadAllLines(yourpath).ToList();
int StartIndex = AllLines.IndexOf(ContainerStartString) + 1;
int EndIndex = AllLines.IndexOf(ContainerEndString) - 1;
List<string> MyLines = AllLines.GetRange(StartIndex, EndIndex);
已经这样做了40年
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENMAME = @"c:'temp'test.txt";
enum State
{
FIND_HEY,
GET_DATA,
FOUND_QUESTION
}
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENMAME);
string inputline = "";
State state = State.FIND_HEY;
while ((inputline = reader.ReadLine()) != null)
{
inputline = inputline.Trim();
if (inputline.Count() > 0)
{
switch (state)
{
case State.FIND_HEY :
if(inputline.ToUpper().Contains("HEY"))
{
state = State.GET_DATA;
}
break;
case State.GET_DATA :
if(inputline.ToUpper().Contains("QUESTION"))
{
state = State.FOUND_QUESTION;
}
else
{
Console.WriteLine(inputline);
}
break;
case State.FOUND_QUESTION :
break;
}
}
}
Console.ReadLine();
}
}
}