簡體   English   中英

以特定方式閱讀和復制文本行

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

我在文本文件中有五行文本,我想通過以下方式進行讀寫:

  1. 讀取第一行並將其復制到新的文本文件1。
  2. 讀取第一行和第二行並將其復制到新的文本文件2。
  3. 讀取第一,第二和第三行並將其復制到新的文本文件3。
  4. 讀取第一,第二,第三和第四行並將其復制到新的文本文件4。
  5. 閱讀所有行並將其復制到新的文本文件5。

我已經嘗試過使用循環的方法,但是我只是感到困惑。 還是使用遞歸...?

那樣的東西(只是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);

我為您創建了一個基本的解決方案。請檢查其余內容,這僅是為您提供幫助。

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