C#向文本文件添加行号

Voj*_*ech 5 c# streamwriter streamreader

我正在尝试在 C# 中读取文本文件并将行号添加到行中。

这是我的输入文件:

    This is line one
    this is line two
    this is line three
Run Code Online (Sandbox Code Playgroud)

这应该是输出:

    1 This is line one
    2 this is line two
    3 this is line three
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我的代码:

class Program
{
    public static void Main()
    {
        string path = Directory.GetCurrentDirectory() + @"\MyText.txt";

        StreamReader sr1 = File.OpenText(path);

        string s = "";

        while ((s = sr1.ReadLine()) != null)           
        {
            for (int i = 1; i < 4; i++)
                Console.WriteLine(i + " " + s);
            }

            sr1.Close();
            Console.WriteLine();    
            StreamWriter sw1 = File.AppendText(path);
            for (int i = 1; i < 4; i++)
            {
                sw1.WriteLine(s);
            }

            sw1.Close();               
    }
}
Run Code Online (Sandbox Code Playgroud)

我 90% 确定我需要使用 for cycle 来获取那里的行号,但到目前为止,使用这段代码我在控制台中得到了这个输出:

1 This is line one
2 This is line one
3 This is line one
1 this is line two
2 this is line two
3 this is line two
1 this is line three
2 this is line three
3 this is line three
Run Code Online (Sandbox Code Playgroud)

这是在输出文件中:

This is line number one.
This is line number two.
This is line number three.1 
2 
3 
Run Code Online (Sandbox Code Playgroud)

我不确定为什么在写入文件时不使用字符串变量 s,即使它是更早定义的(另一个块,可能是另一个规则?)。

Giu*_*olo 2

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace AppendText
{
    class Program
    {
        public static void Main()
        {
            string path = Directory.GetCurrentDirectory() + @"\MyText.txt";

            StreamReader sr1 = File.OpenText(path);


            string s = "";
            int counter = 1;
            StringBuilder sb = new StringBuilder();

            while ((s = sr1.ReadLine()) != null)
            {
                var lineOutput = counter++ + " " + s;
                Console.WriteLine(lineOutput);

                sb.Append(lineOutput);
            }


            sr1.Close();
            Console.WriteLine();
            StreamWriter sw1 = File.AppendText(path);
            sw1.Write(sb);

            sw1.Close();

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Chris,抱歉没有意识到这是作业。删掉我的帖子就可以了?!:) (2认同)