We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,687 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Reading and copying few lines based on some condition in a text file

Hi,
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))

                file1.WriteLine(line);
        }

        file.Close();
4
Contributors
2
Replies
1 Day
Discussion Span
10 Months Ago
Last Updated
4
Views
jumboora
Light Poster
30 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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.

pritaeas
Posting Prodigy
Moderator
9,265 posts since Jul 2006
Reputation Points: 1,173
Solved Threads: 1,456
Skill Endorsements: 86

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.

Cameronsmith63
Junior Poster in Training
74 posts since May 2010
Reputation Points: 19
Solved Threads: 4
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0559 seconds using 2.65MB