I am a newbie in C#. I am trying to read a text file line by line (each line has fixed length of 128 numerical values). Text file has more than 300 lines. Now i want to select and copy each line after 5 lines (i.e., interval = 5 or 10) to another text file. For Example, if there are 7 lines and interval is 2, then it should select line 1 and 4 and 7. (2,3 and 5,6 should be skipped because of interval).
I have written a small code which reads a text file line by line until end of line. but i don't know how to put interval. Any help plz!
Inline Code Example Here

        string line;
        int interval = 2;
        // Read the file and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader(@"F:\shoe1.txt");

        while ((line = file.ReadLine()) != null)
           // I think interval condition should be used here but i don't know how
            using (System.IO.StreamWriter file1 = new System.IO.StreamWriter(@"F:\WriteLines2.txt", true))


4 Years
Discussion Span
Last Post by Cameronsmith63

You can use modulus. If interval is 2, that means that every third line is written. Initialize a variable to 0 before the loop, then check before writing if that variable modulus (interval + 1) equals zero. Increment at the end of your loop.


int count = 0;

increment the count by 1 during each loop then you mod count.
if count mod 5 = 0 then writeline.

Something like that.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.