简体   繁体   中英

count lines from text file and count it in 1 line

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);
    }
}

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
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM