我正在尝试用 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/