如何在c#中选择和重写文本文件的特定部分?

时间:2016-01-08 09:45:28

标签: c# file

我有一个文本文件如下:

  

22 3
  18 10 10
  0 0 0 0 2 3 2
  15 9 0 0 1 20
  17 9 0 0 1 17

我将此文本文件读作:

int counter = 0;
string line;
StreamReader file = new StreamReader("../../normal.txt");
while ((line = file.ReadLine()) != null)
{
   Console.WriteLine(line);
   counter++;
}

之后,我想删除前两行。除此之外,选择剩余行中的第一个和第三个字符,并在已经读取的文本下重写它们。这样最终的输出就是:

  

22 3
  18 10 10
  0 0 0 0 2 3 2
  15 9 0 0 1 20
  17 9 0 0 1 17
  0 0
  15 0
  17 0

我该怎么做?

3 个答案:

答案 0 :(得分:3)

这样的事情怎么样:

List<string> lineList = new List<string>();
while ((line = file.ReadLine()) != null)
{
    Console.WriteLine(line);
    lineList.add(line);
    counter++;
}

for(int i = 2; i < lineList.Count; i++) {
    string[] split = lineList[i].Split(new char[] {' '});
    Console.WriteLine(string.Format("{0} {1}", split[0], split[2]));
}

答案 1 :(得分:0)

获取指定的输出;

List<string> data = new List<string>();
List<string> lines = File.ReadAllLines("../../normal.txt").ToList();

foreach (string item in lines.Skip(2))
{
    data = item.Split(new char[] {' '}).ToList();
    lines.Add(string.Format("{0} {1}", data[0], data[2]);
}

答案 2 :(得分:0)

     var existingLines = File.ReadAllLines("../../normal.txt");
     var newLines = new List<string>();
     var appendedLines = new List<string>();

     for (var i = 2; i < existingLines.Length; i++)
     {
            // add a line
            newLines.Add(existingLines[i]);

            // add first and third character to the line
            var split = existingLines[i].Split(' ');
            appendedLines.Add(string.Format("{0} {1}", split[0], split[2]));
     }
     newLines.AddRange(appendedLines);

     File.WriteAllLines("../../newText.txt", newLines);