C# - Foreach two line in Text File

C# - Foreach two line in Text File

file.readlines c#
c# file.readlines vs streamreader
c# find specific line in text file
c# read text file line by line to array
c# reading lines from file
file.readalllines c#
c# read in a text file line by line
c# read file line by line using

I am developing in C#. I have a text file containing the following:


I want to iterate through this file two line by two line, then print to the console the first line, second line (the Name and the Country) of each couple, so the output would be:

Sam, NYC
Mii, Peru

Here is what I have tried:

int linenum = 0;
        foreach (string line in File.ReadLines("c:\\file.txt"))
            string word = line;
            string s = "";
            string j = "";
            linenum = linenum + 1;
            if(linenum % 2 != 0) //impaire
                s = line;
                j = line;
          Console.WriteLine((string.Concat(s, j));

But that's not working, I want to do:

 int linenum = 0;
 foreach( two lines in File.ReadLines("c:\\file.txt"))
 linenum = linenum + 1;
 //get the first line (linenum = 1) and store it in a string s
 // then get the second line (linenum = 2) and store it in a string j
 // then print the two strings together to the console like that 
  Console.WriteLine((string.Concat("S: " + s,"J: " j));

How can I do that ?

You do your output with Console.WriteLine in every line, but you also should do that only for every second line. Furthermore, your variables s and j live inside the loop's scope, so they are recreated with every iteration and loose their prior value.

int i = 0; string prev = "";
foreach (string line in File.ReadLines("c:\\file.txt")) {
    if (i++ % 2 == 0) prev = line;
    else Console.WriteLine($"{prev}, {line}");

Another approach would be iterating the array you get from File.ReadAllLines with an for loop instead of foreach and increase the index by 2

var lines = File.ReadAllLines("c:\\file.txt");
//make sure, you have an even number of lines!
if (lines.Length% 2 == 0) for (int i = 0; i < lines.Length; i+=2) {
   Console.WriteLine($"{lines[i]}, {lines[i+1]}");  

C# File.ReadLines, Use foreach Over Strings, ReadLines using System; using System.IO; class Program { static void Main() { // Read in lines from file. foreach (string line in File.ReadLines("c:\\file.txt")) {  Important: With File.ReadLines, the foreach-loop is the best syntax as it avoids copying the IEnumerable to another collection in memory. Foreach IEnumerable C# program that uses File.ReadLines using System; using System.IO; class Program { static void Main() { // Read in lines from file.

Use File.ReadAllLines to return an array of strings:

var lines = File.ReadAllLines(filePath);
for (int i = 0; i < lines.Length; i+=2)
    var s = lines[i];
    var j = lines[i+1];
    Console.WriteLine($"S: {s} J: {s}");

Ruby File Handling: File and IO Classes, Handle files: open a file with File.open and sequentially read in each line until eof​. IO.foreach("/perls/file.txt") {|line| puts line.length} Output Line one Line two  How to: Read a Text File One Line at a Time (Visual C#) This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and displayed on the screen.

You can write yourself a little helper method to return batches of lines.

This implementation handles files that are not a multiple of the batch size (2 in your case) by returning "" for the missing lines at the end of the file.

public static IEnumerable<string[]> BatchedLinesFromFile(string filename, int batchSize)
    string[] result = Enumerable.Repeat("", batchSize).ToArray();
    int count = 0;

    foreach (var line in File.ReadLines(filename))
        result[count++] = line;

        if (count != batchSize)

        yield return result;
        count  = 0;
        result = Enumerable.Repeat("", batchSize).ToArray();

    if (count > 0)
        yield return result;

Note that this also returns a separate array for each result, in case you make a copy of it.

Given that code, you can use it like so:

foreach (var batch in BatchedLinesFromFile(filename, 2))
    Console.WriteLine(string.Join(", ", batch));

Xamarin Doctor - C#, I am developing in C#. I have a text file containing the following: Sam NYC Mii Peru LEO Argentina I want to iterate through this file two line by  File.ReadLines() method to read a text file that has lots of lines. File.ReadLines() method internally creates Enumerator. So we can call it in the foreach and every time foreach asks for a next value, it calls StreamReader.Re­adLine under the hood. C# Code: You can use File.ReadLines and foreach  to  read  whole  file line by line

Actually, you can use LINQ to get two lines in a time using Take

var twoLines = File.ReadLines(@"YourPath").Take(2));

As you can use Skip to skip the two lines you took and take the next two lines like :

var twoLines = File.ReadLines(@"YourPath").Skip(2).Take(2));

EDIT : Thanks for @derpirscher there were a performance issue so changed the code to the following :

first read the whole file and store it in a string array then loop through it using LINQ to take two elements from the array in a time.

string[] myStringArray = File.ReadAllLines(@"YourFile.txt");
for (int i = 0; i < myStringArray.Length ; i+=2)
      var twoLines = myStringArray.Skip(i).Take(2).ToArray();

Reading a text file line by line, You may often find yourself with the need to read a file line-by-line and extract information from each processed line; think of a logfile. These examples show various ways to write text to a file. The first two examples use static convenience methods on the System.IO.File class to write each element of any IEnumerable<string> and a string to a text file. Example 3 shows how to add text to a file when you have to process each line individually as you write to the file.

Another one, using Enumerable.Repeat() and an interger selector incremented a [NumberOfLines / 2] times. Could be interesting for the LINQ addicted (a for / foreach solution is probably better anyway).

string[] input = File.ReadAllLines([SourcePath]);
int Selector = -1;

string[] output = Enumerable.Repeat(0, input.Length / 2).Select(_ => {
                    Selector += 2;
                    return $"{input[Selector - 1]}  {input[Selector]}";

The output is:

Mii Peru
LEO Argentina

Read Text File [C#], Every time foreach asks for a next value, it calls StreamReader.ReadLine under the hood. [C#] foreach (string line in File.ReadLines(  Compiling the Code. Copy the code and paste it into a C# console application. If you are not using the text files from How to: Write to a Text File, replace the argument to ReadAllText and ReadAllLines with the appropriate path and file name on your computer.

C#, How to Read and Write a Text File in C#? · 5 Best Programming Languages For Newbies · How to Execute C# Program on cmd (command-line)? · What is .NET 3​-  This step-by-step article describes how to read from and write to a text file by using Visual C#. back to the top Requirements The following list outlines the recommended hardware, software, network infrastructure, and service packs that you must have:

ForEach-Object, Starting in Windows PowerShell 3.0, there are two different ways to construct a Next, the Process parameter uses the Out-File cmdlet to create a text file that is Typing Ctrl + C at the command line stops a running ForEach-Object -Parallel  foreach (var batchOfLines in File.ReadLines(filePath).Batch(1000)) { // batchOfLines contains up to 1000 lines of your file. var paths = ComputeStrongestPaths(batchOfLines.ToArray()); } The important thing here is that you use ReadLines and not Read All Lines as the latter will load the whole file into memory.

Write a simple parallel program using Parallel.ForEach, If you are not familiar with lambda expressions in C# or Visual Basic, see Lambda expressions in PLINQ and TPL. You can modify the two paths as necessary. ForEach(files, (currentFile) => { // The more computational work you do NET Core console application from the command line, use dotnet run  when i run this instead of getting two lines i get only one whats even more strange is it only output the second line and not the first line so my result in this case is 210,Joseph,Alonzo,2900,23/10/2010 and if only 1 occurence had 23/10/2010 in the line then im getting empty results so I really need help with this one! Thanks