c#在txt文件中搜索字符串

我想在txt文件中找到一个字符串,如果字符串比较,它应该继续阅读行,直到我用作参数的另一个字符串。

例:

CustomerEN //search for this string ... some text wich has details about 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> groups = new List>(); List current = null; foreach (var line in File.ReadAllLines(pathToFile)) { if (line.Contains("CustomerEN") && current == null) current = new List(); else if (line.Contains("CustomerCh") && current != null) { groups.Add(current); current = null; } if (current != null) current.Add(line); } 

你必须使用while因为foreach不知道索引。 下面是一个示例代码。

 int counter = 0; string line; Console.Write("Input your search text: "); var text = Console.ReadLine(); System.IO.StreamReader file = new System.IO.StreamReader("SampleInput1.txt"); while ((line = file.ReadLine()) != null) { if (line.Contains(text)) { break; } counter++; } Console.WriteLine("Line number: {0}", counter); file.Close(); Console.ReadLine(); 

使用LINQ,您可以使用SkipWhile / TakeWhile方法,如下所示:

 var importantLines = File.ReadLines(pathToTextFile) .SkipWhile(line => !line.Contains("CustomerEN")) .TakeWhile(line => !line.Contains("CustomerCh")); 

如果你只有一个第一个字符串,你可以使用简单的for循环。

 var lines = File.ReadAllLines(pathToTextFile); var firstFound = false; for(int index = 0; index < lines.Count; index++) { if(!firstFound && lines[index].Contains("CustomerEN")) { firstFound = true; } if(firstFound && lines[index].Contains("CustomerCh")) { //do, what you want, and exit the loop // return lines[index]; } } 

我工作了一点Rawling在这里发布的方法,直到最后在同一个文件中找到多行。 这对我有用:

  foreach (var line in File.ReadLines(pathToFile)) { if (line.Contains("CustomerEN") && current == null) { current = new List(); current.Add(line); } else if (line.Contains("CustomerEN") && current != null) { current.Add(line); } } string s = String.Join(",", current); MessageBox.Show(s);