C# 如何来回遍历文本文件行
我有一个文本文件,其中包含我需要处理的行。以下是文本文件中的行格式C# 如何来回遍历文本文件行,c#,string,char,substring,text-files,C#,String,Char,Substring,Text Files,我有一个文本文件,其中包含我需要处理的行。以下是文本文件中的行格式 07 IVIN 15:37 06/03 022 00:00:14 600 2265507967 0:03 08 ITRS 15:37 06/03 022 00:00:09 603 7878787887 0:03 08 ITRS 15:37 06/03 022 00:00:09 603 2265507967 0:03 现在,根据
07 IVIN 15:37 06/03 022 00:00:14 600 2265507967 0:03
08 ITRS 15:37 06/03 022 00:00:09 603 7878787887 0:03
08 ITRS 15:37 06/03 022 00:00:09 603 2265507967 0:03
现在,根据我的要求,我必须逐行阅读此文本文件。现在,只要我将ITRS
放入任何一行,我就必须在文本文件行的正上方搜索编号2265507967
。只要它在正上方的行中找到2265507967
,它就应该读取该行。
现在,我将这些行读入字符串,并根据空格将其拆分为字符
var strings = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
我的问题是,我无法遍历文本文件的上部并搜索子字符串
2265507967
。请提供帮助。我不知道在读取文件时是否可以后退(使用seek()
方法除外),但我可能错了
更简单的方法是:
ITRS
,则从该行获取值并检查字典。一旦找到它,请清除字典并返回步骤1
b。如果不包含ITRS
,只需将数字和行作为键值对添加即可//Initialization
Dictionary<string, string> previousLines = new Dictionary<string, string>();
TextReader tw = new TextReader(filePath);
string line = String.Empty;
//Read the file one line at a time
while((line = tw.ReadLine()) != null)
{
if(line.contains("ITRS")
{
//Get the number you will use for searching
string number = line.split(new char[]{' '})[4];
//Use the dictionary to read a line you have previously read.
string line = previousLines[number];
previousLines.Clear(); //Remove the elements so that they do not interrupt the next searches. I am assuming that you want to search between lines which are found between ITRS tags. If you do not want this, simply omit this line.
... //Do your logic here.
}
else
{
string number = line.split(new char[]{' '})[4];
previousLines.Add(number, line);
}
}
//初始化
Dictionary previousLines=新字典();
TextReader tw=新的TextReader(文件路径);
string line=string.Empty;
//一次读取一行文件
而((line=tw.ReadLine())!=null)
{
如果(第行包含(“ITRS”)
{
//获取用于搜索的号码
字符串编号=line.split(新字符[]{''})[4];
//用字典读你以前读过的一行。
字符串行=前几行[编号];
previousLines.Clear();//删除元素,以便它们不会中断下一次搜索。我假设您希望在ITRS标记之间找到的行之间进行搜索。如果不希望这样做,只需省略这一行即可。
…//在这里讲你的逻辑。
}
其他的
{
字符串编号=line.split(新字符[]{''})[4];
上一行。添加(数字、行);
}
}
只需保存上一行的副本。不清楚您想要实现什么。但是,如果您需要查看当前行的上方或下方,最好将所有内容读取到内存中。最简单的方法是使用文件。ReadAllLines
返回字符串[]
所有行。请用语法进行说明。如果有10000行要添加到字典中,我将无法获取它。这会使我的过程变慢吗?@Ram:我已经更新了我的答案。它应该能够处理那么多的字符串,但我建议您对操作进行基准测试。