[c#] c# search string in txt file

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.

This question is related to c# string file-io

The answer is


If you whant only one first string, you can use simple for-loop.

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];
   }
}

I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:

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

With LINQ, you could use the SkipWhile / TakeWhile methods, like this:

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

You have to use while since foreach does not know about index. Below is an example code.

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();

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js