【发布时间】:2011-12-01 08:46:03
【问题描述】:
我正在尝试读取 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,即使它是之前定义的(另一个块,可能是另一个规则?)。
【问题讨论】:
-
一般评论:我认为最好有 using(StreamReader){} 和 using(StreamWriter){} 块。而且你应该将你的变量命名为's''line',这更清楚,因为它是一条线:)
-
我不知道这是问题还是您的代码有问题,但是您的括号不匹配。 while 循环的关闭时间比您从缩进中想象的要早。
-
你为什么一直从
1循环到4?你想每行重复四次吗? -
@Dan Abramov 不,我认为我需要一个 for 循环来为行编号,但这是我对解决方案的印象,我之前错了
-
+1 用于尝试家庭作业问题并显示代码。这么多作业题都是“给我密码”的形式,根本不费吹灰之力
标签: c# streamreader streamwriter