简体   繁体   English

以特定方式阅读和复制文本行

[英]reading and copying lines of text in a specific way

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. 读取第一行并将其复制到新的文本文件1。
  2. read 1st and 2nd line and copy them to new text file 2. 读取第一行和第二行并将其复制到新的文本文件2。
  3. read 1st, 2nd and 3rd line and copy them to new text file 3. 读取第一,第二和第三行并将其复制到新的文本文件3。
  4. read 1st, 2nd, 3rd and 4th line and copy them to new text file 4. 读取第一,第二,第三和第四行并将其复制到新的文本文件4。
  5. read all lines and copy them to new text file 5. 阅读所有行并将其复制到新的文本文件5。

I have tried something with loops, but I just get confused. 我已经尝试过使用循环的方法,但是我只是感到困惑。 Or maybe to use recursion....? 还是使用递归...?

Something like that (just Linq with Take ) 那样的东西(只是LinqTake

// ..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);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM