开发者

C# add line numbers to a text file

开发者 https://www.devze.com 2023-04-10 15:12 出处:网络
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

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()) != nul开发者_StackOverflow中文版l)           
        {
            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);


OPEN STREAM

read the whole line and store it in a temp variable. Use a counter to keep track which line you have read. concatenate the counter with the temp variable. save it to the file. move your line pointer to next line and repeat.

THEN CLOSE YOUR STREAM


I could provide you the right code, but because it is home work I will just ask you question that should lead you to the right answer:

  • why do you close the StreamReader the while inside your loop ? You will still access it after, that can cause an error.
  • why do you write in your StreamWriter without the prepended index ?
  • Why do you open the StreamWriter inside the loop ? Wouldn't it be better to open the StreamWriter and StreamReader outside the loop. Do you job in the loop and then close the Streams ?


You need to prepend the line number to each line string. Check out String.Format. Also, try a counter variable that sits outside the while loop to keep the line number count.

Hopefully that's enough to get you on the right path without handing you the exact answer.


Are you sure you want to close stream inside the loop while?


Watch out the FOR loops, you put them inside the While, so basically you are saying:

while ((s = sr1.ReadLine()) != null)

Every row read

for (int i = 1; i < 4; i++)

Repeat 3 times a write.

Also, you are closing the stream inside the while, so after the first row read.


Here is one major issue for you:

        for (int i = 1; i < 4; i++)
            Console.WriteLine(i + " " + s);
        }

You are closing the for loop with a curly brace but not using a curly brace to open it. This means that the curly brace quoted above is actually closing the while loop so you loop through doing all the console.writeline and then when you come to writing to the file you are actually not reading from the file at all - s is "" due to scoping.


An alternative to @Hasan's answer for in-memory strings as a one-liner:

function AddLineNumbers(string input) => 
    String.Join('\n', input.Split('\n').Select((text, i) => $"{i+1}: {text}"));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号