C# 向文本文件添加行号

标签 c# streamreader streamwriter

我正在尝试用 C# 读取文本文件并向行添加行号。

这是我的输入文件:

    This is line one
    this is line two
    this is line three

这应该是输出:

    1 This is line one
    2 this is line two
    3 this is line three

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

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();               
    }
}

我 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

这是在输出文件中:

This is line number one.
This is line number two.
This is line number three.1 
2 
3 

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

最佳答案

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();

        }

    }
}

关于C# 向文本文件添加行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7659756/

相关文章:

C# process.Kill 不会立即停止正在运行批处理文件的进程

c# - 将 .csv 文件加载到字典中,我不断收到错误 "cannot convert from ' string[ ]' to ' string'"

使用 StreamWriter 写入文本文件时出现 C# OutOfMemoryException

c# - 如何将可观察集合写入txt文件?

c# - 调用 Stream.Write 和使用 StreamWriter 有什么区别?

c# - 通用类型父列表不接受子类型是父列表类型的子类型

C# string.remove 和 Regex.Match

c# - IIS WCF 服务托管与 Windows 服务

c# - 在 Javascript 函数中使用特殊字符作为参数值时出现 Javascript 错误

c# - 从 Request.Files、StreamReader 或 BinaryReader 或 BufferedStream 读取上传文件的最佳方式是什么?