我试图读取C#中的文本文件并将行号添加到行中。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%需要使用循环来获取行号,但到目前为止,使用此代码我可以在控制台中获得该输出:
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,另一个规则可能?)。
一般评论:我认为最好使用(StreamReader){}和使用(StreamWriter){}块。而且你也应该命名你的变量的''行',这是更清晰的,因为它是一个行:) –
我不知道这是问题或你的代码的问题,但你的括号不匹配。 while循环比您从缩进中想到的更早关闭。 – Ray
为什么你要从'1'循环到'4'?你想重复每一行四次吗? –