I am trying to read a text file in C# and add line numbers to the lines.
This my input file:
This is line one
this is line two
this is line three
And this should be the output:
1 This is line one
2 this is line two
3 this is line three
This is my code so far:
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();
}
}
I am 90% sure I need to use for cycle to get the line numbers there but so far with this code I get this output in the console:
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
And this is in the output file:
This is line number one.
This is line number two.
This is line number three.1
2
3
I am not sure why the string variable s is not used when writing in the file even though it is defined earlier (another block, another rules maybe?).
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();
}
}
}
IEnumerable<string> lines = File.ReadLines(file)
.Select((line,i)=>i + " " + line)
.ToList();
File.WriteAllLines(file, lines);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With