Reputation: 1
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);
}
}
Upvotes: 0
Views: 323
Reputation: 1719
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.
Upvotes: 1
Reputation: 16049
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
}
}
Upvotes: 1