我想在 txt 文件中找到一个字符串,如果字符串比较,它应该继续读取行,直到我用作参数的另一个字符串。
Example:
CustomerEN //search for this string
...
some text which has details about the customer
id "123456"
username "rootuser"
...
CustomerCh //get text till this string
否则我需要详细信息才能与他们合作。
我正在使用 linq 搜索“CustomerEN”,如下所示:
File.ReadLines(pathToTextFile).Any(line => line.Contains("CustomerEN"))
但现在我不得不阅读行(数据)直到“CustomerCh”来提取详细信息。
如果您的两行仅在文件中出现一次,您可以使用
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.Skip(1) // optional
.TakeWhile(line => !line.Contains("CustomerCh"));
如果一个文件中可能出现多次,那么最好使用常规的foreach
循环 - 读取行,跟踪您当前是在客户内部还是外部等:
List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
current = new List<string>();
else if (line.Contains("CustomerCh") && current != null)
{
groups.Add(current);
current = null;
}
if (current != null)
current.Add(line);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)