0

So what I want to do its count lines from a text file and count them in 1 line on the console window. This is what I have now, it works but it writes lot of lines to the console and I want it to change the count on 1 line every second.

long lines = 0;
using (StreamReader r = new StreamReader("text.txt"))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
          count++;
          Console.Title = "Count: " + lines;
          Console.WriteLine(Console.Title);
    }
}
Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
maybe
  • 1
  • 2

2 Answers2

1

You can use File.ReadAllLiness(<filePath>).Count() to get count of lines in text file.

Console.WriteLine(File.ReadAllLiness("text.txt").Count())

Your code is not working because you are printing lines variable which is assigned as 0 at the beginning, but not updated anywhere.

Either try my first solution or use lines variable instead of count in your existing program and print it out of while loop

long lines = 0;
using (StreamReader r = new StreamReader("text.txt"))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
        Console.WriteLine(++lines); //One line solution
    }
}
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • yeah k but i want its do " live " count in the Console.WriteLine – maybe Feb 07 '20 at 11:51
  • Count.. 8076 Count.. 8077 Count.. 8078 Count.. 8079 Count.. 8080 Count.. 8081 Count.. 8082 Count.. 8083 its what its write (write lot of lines in console.. https://i.imgur.com/bp4tqIz.png) ^ i want to do it every 1 line its count so its write but in 1 line – maybe Feb 07 '20 at 11:56
  • its pretty simple write `Console.WriteLine()` inside while loop, so that when `StreamReader` reads one line print it on Console. I would suggest you to read about `StreamReader` and also `File` operations in C#. It will really helpful for you – Prasad Telkikar Feb 07 '20 at 11:58
  • I can not find any other way to minimize above code to make it one liner. – Prasad Telkikar Feb 07 '20 at 12:19
1

You should take a look at this topic:

How can I update the current line in a C# Windows Console App?

It is possible to update the current line. All you need to add is a logic to only do it once per second.

Maybe something like this:

long lines = 0;
var lastSecond = DateTime.Now.Second;
using (var r = new StreamReader("text.txt"))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
        lines++;
        Console.Title = "Count: " + lines;
        if(lastSecond != DateTime.Now.Second)
            Console.Write("\r{0}   ", Console.Title);
        lastSecond = DateTime.Now.Second;
    }
    Console.WriteLine(""); // Create new line at the end
}

There will be nicer ways to update once per second but the main problem seems to be how to update the current console output.

Sebastian
  • 1,569
  • 1
  • 17
  • 20