Я пытаюсь прочитать текстовый файл на С# и добавить номера строк к строкам.
Это мой входной файл:
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 не используется при записи в файл, хотя она определена ранее (другой блок, может быть, другие правила?).
1
к4
? Вы хотите повторить каждую строку четыре раза? - person Dan Abramov   schedule 05.10.2011