Reputation: 2009
I'm trying to display percentages of loading in the same place
and I found solution on that
Console.Write($"\r{ (double) (i+1) * 100 / list.Count }% - {text}");
but after the percentage I'd want to display some text which has different lengths e.g something between 20-40 characters
The problem with this approach is that if "new" line is shorter than "previous" then some part of "previous" text still remains there.
I managed to write 'hack' which overwrites current line with spaces (clears it) and then writes my line
Console.Write($"\r ");
Console.Write($"\r{ (double) (i+1) * 100 / list.Count }% - {text}");
Is there an better solution to do that?
Upvotes: 0
Views: 172
Reputation: 2547
The easiest way to do this is generally with
var stringOfLengthMaxWithSpacestoLeft = yourString.PadLeft(MaxStringLength, ' ');
or
var stringOfLengthMaxWithSpacestoRight = yourString.PadRight(MaxStringLength, ' ');
If you want to clear the line, all you have to do is use the backspace character and then overwrite with with the same length, i.e.
for (var i = 0; i++; i < MaxStringLength)
Console.Write("\b");
Then you can start writing again.
Upvotes: 1