我試圖讀取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'?你想重複每一行四次嗎? –