我有一个文本文件,其中特定字符在每几行之后在行的开头重复。没有。两者之间的线不固定。我能够找出出现这种情况的那些线。我想阅读其中的那些内容。
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
我必须阅读两者之间的界限。每次条件都保持不变。感谢。
答案 0 :(得分:3)
您似乎只需跳过符合特定条件的行。
var lines = System.IO.File.ReadLines(@"text file")
.Where (line => ! line.StartsWith("Condition");
foreach(string line in lines)
{
// do your stuff
}
答案 1 :(得分:2)
我假设您要解析文本文件并在每次条件之间处理所有文本块。
基本上你读取每一行,检查第一个条件,它指示“块”的开始并继续读取行,直到找到另一个条件,这表示块的结束(和另一个的开始)。
洗涤,冲洗,重复。
一个简单的例子:
using (var reader = new StreamReader(@"test.txt"))
{
var textInBetween = new List<string>();
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);
}
}
答案 2 :(得分:1)
如果我理解正确,你想在“块内外”的条件之间切换:
{
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.
}
}
}
答案 3 :(得分:1)
这是我经常使用的方法,用于读取对于XDocument来说太大的xml文件。根据您的需要修改它会非常容易。
public static void ReadThroghFile(string filePath, int beingLinesToSkip, string endingMarker, Action<string> 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;
}
}
}
答案 4 :(得分:0)
除非我遗漏了某些内容,否则您似乎 从StreamReader中读取“每一行” 并检查您的“条件”是否满足。所以我不明白你的问题“我想在两者之间阅读这些内容。”!!!!
答案 5 :(得分:0)
你能不能做你想做的事吗?
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
}