阅读文本文件块
我有一个文本文件,其中特定字符在每几行之后在行的开头重复。 没有。 中间的线不固定。 我能够找出出现这种情况的那些线。 我想阅读其中的那些内容。
using (StreamReader sr = new StreamReader(@"text file")) { string line; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("some character"))
因为下次出现这个字符时,代码保持不变。 我无法阅读其中的那些内容
例如。
Condition at the begining of a line Next line Next line Condition at the begining of a line Next Line Next Line Next Line Next Line Condition at the begining of a line
我必须阅读两者之间的界限。 每次条件都保持不变。 谢谢。
我假设您要解析文本文件并在每次条件之间处理所有文本块。
基本上你读取每一行,检查第一个条件,它指示“块”的开始并继续读取行,直到找到另一个条件,这表示块的结束(和另一个的开始)。
洗涤,冲洗,重复。
一个简单的例子:
using (var reader = new StreamReader(@"test.txt")) { var textInBetween = new List(); bool startTagFound = false; while (!reader.EndOfStream) { var line = reader.ReadLine(); if (String.IsNullOrEmpty(line)) continue; if (!startTagFound) { startTagFound = line.StartsWith("Condition"); continue; } bool endTagFound = line.StartsWith("Condition"); if (endTagFound) { // Do stuff with the text you've read in between here // ... textInBetween.Clear(); continue; } textInBetween.Add(line); } }
看来你只需要跳过符合某种传统的线条。
var lines = System.IO.File.ReadLines(@"text file") .Where (line => ! line.StartsWith("Condition"); foreach(string line in lines) { // do your stuff }
如果我已正确理解,您想要在“块内部或外部”条件之间切换:
{ string line; int inside = 0; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("some character")) { inside = !inside; // If you want to process the control line, do it here. continue; } if (inside) { // "line" is inside the block. The line starting with "some character" // is never here. } else { // Well, line is outside. And the control lines aren't here either. } } }
这是我经常使用的方法,用于读取对于XDocument来说太大的xml文件。 根据您的需要修改它会非常容易。
public static void ReadThroghFile(string filePath, int beingLinesToSkip, string endingMarker, Action action) { using (var feed = new StreamReader(filePath)) { var currentLine = String.Empty; var ongoingStringFromFeed = String.Empty; for (var i = 0; i < beingLinesToSkip; i++) feed.ReadLine(); while ((currentLine = feed.ReadLine()) != null) { ongoingStringFromFeed += currentLine.Trim(); if (!currentLine.Contains(endingMarker)) continue; action(ongoingStringFromFeed); ongoingStringFromFeed = String.Empty; } } }
除非我遗漏了某些内容,否则您似乎正在阅读 StreamReader中的“每一行”并检查您的“条件”是否满足。 所以我不明白你的问题“我想在两者之间阅读这些内容。”!!!!
难道你不能做你想做你想做的事吗?
using (StreamReader sr = new StreamReader(@"text file")) { string line; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("some character")) { //Get rid of line } else { // Do stuff with the lines you want }