c# search string in txt file
c#, file-io, string
Solution
If your pair of lines will only appear once in your file, you could use
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.Skip(1) // optional
.TakeWhile(line => !line.Contains("CustomerCh"));
If you could have multiple occurrences in one file, you're probably better off using a regular `foreach` loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:
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);
}
Problem
I want to find a string in a txt file if string compares, it should go on reading lines till another string which I'm using as parameter. Example: ``` CustomerEN //search for this string ... some text which has details about the customer id "123456" username "rootuser" ... CustomerCh //get text till this string ``` I need the details to work with them otherwise. I'm using linq to search for "CustomerEN" like this: ``` File.ReadLines(pathToTextFile).Any(line => line.Contains("CustomerEN")) ``` But now I'm stuck with reading lines (data) till "CustomerCh" to extract details.