reading and copying lines of text in a specific way

116 views Asked by At

I have five lines of text in a text file that I want to read and write in the following way:

  1. read 1st line and copy it to new text file 1.
  2. read 1st and 2nd line and copy them to new text file 2.
  3. read 1st, 2nd and 3rd line and copy them to new text file 3.
  4. read 1st, 2nd, 3rd and 4th line and copy them to new text file 4.
  5. read all lines and copy them to new text file 5.

I have tried something with loops, but I just get confused. Or maybe to use recursion....?

2

There are 2 answers

0
Marc On

I created a basic solution for you.. Please check for the rest, this is just for help you out.

List<String> lines = File.ReadLines(@"C:\Users\m\Desktop\te\source.txt").ToList();
string basicPath = @"C:\Users\m\Desktop\te\";

int i = 1;
foreach (string line in lines)
{
    File.WriteAllLines(basicPath + i + ".txt", lines.GetRange(0, i));
    i++;
}
1
Dmitry Bychenko On

Something like that (just Linq with Take)

// ..Or ReadAllLines to cache the file lines
var source = File.ReadLines(@"C:\MyText.txt");

File.WriteAllLines(@"C:\target1.txt", source.Take(1));
File.WriteAllLines(@"C:\target2.txt", source.Take(2));
File.WriteAllLines(@"C:\target3.txt", source.Take(3));
File.WriteAllLines(@"C:\target4.txt", source.Take(4));

// not 5 lines, but entire file
File.WriteAllLines(@"C:\target5.txt", source);