0

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?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Joelty
  • 1,751
  • 5
  • 22
  • 64
  • If you know the length of the previous text you can write as many Backspace characters (`\b`) to the console and the do the `Console.Write`. See also https://stackoverflow.com/a/5195807/2137237 – Markus Deibel Jan 29 '19 at 10:36

1 Answers1

1

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.

tigerswithguitars
  • 2,497
  • 1
  • 31
  • 53