artoon
artoon

Reputation: 739

Clearing a line in the console

How can a line in the console be cleared in C#?

I know how to place the cursor at the beginning of a line:

Console.SetCursorPosition(0, Console.CursorTop);

Upvotes: 7

Views: 28659

Answers (6)

Shafiq Jetha
Shafiq Jetha

Reputation: 1556

This worked well enough for me in my little toy example:

Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.Write(Enumerable.Repeat(' ', Console.BufferWidth).ToArray());
Console.WriteLine($"\rProcessing row {table.IndexOf(row)} of {table.Count}");

I don't know if it takes care of things like wrapping over long lines, but it combines a few of the answers already provided, it's easy to understand and it gets the job done for me.

Upvotes: 0

xVice1337
xVice1337

Reputation: 7

Well i think most of the answers here arent really that robust.

I guess this is solved allready but yk:

private static void ClearPrint(string msg)
{
    Console.WriteLine($"\r{msg}{new String(' ', Console.BufferWidth - msg.Length)}");
}

Upvotes: -1

Thomas Ertl
Thomas Ertl

Reputation: 122

After setting the cursor position, you can use backspace:

do { Console.Write("\b \b"); } while (Console.CursorLeft > 0);

Upvotes: 1

knocte
knocte

Reputation: 17919

(Combining at.toulan and Andrew's answers here.)

Simplest is, to overwrite over the last line:

Console.SetCursorPosition(0, Console.CursorTop - 1)
Console.WriteLine("new line of text");

If "new line of text" is shorter than the text that was there before, write spaces before writing your text, like Andrew says.

Upvotes: 3

aj.toulan
aj.toulan

Reputation: 1432

Once the last space of a console buffer row is used, the console cursor automatically jumps to the next line.

  1. Reset cursor back to the beginning before it reaches edge of console
  2. Erase old console output, placing cursor on next line
  3. Reset cursor back onto the line that was just cleared

    while (true)
    {
      Console.Write(".");
      if (Console.CursorLeft + 1 >= Console.BufferWidth)
      {
        Console.SetCursorPosition(0, Console.CursorTop);
        Console.Write(Enumerable.Repeat<char>(' ', Console.BufferWidth).ToArray());
        Console.SetCursorPosition(0, Console.CursorTop - 1);
      }
    
      if (Console.KeyAvailable)
        break;
    }
    

Upvotes: 4

Andrew Cooper
Andrew Cooper

Reputation: 32576

Simplest method would be to move to the start of the line, as you have done, and then write out a string of spaces the same length as the length of the line.

Console.Write(new String(' ', Console.BufferWidth));

Upvotes: 14

Related Questions