C# clear Console last Item and replace new? Console Animation

PawanS picture PawanS · Feb 17, 2011 · Viewed 35.1k times · Source

The following CSharp Code(just sample):

Console.WriteLine("Searching file in...");

foreach(var dir in DirList)
{
    Console.WriteLine(dir);
}

Prints Output As:

Searching file in...

dir1

dir2

dir3

dir4

.

.

.

Question? How can I get the output as

Searching file in...

dir1  

(then clear dir1 and print dir2 and so on)All next dir name wiil replace the previous dir

Answer

digEmAll picture digEmAll · Feb 17, 2011

Use Console.SetCursorPosition to set the cursor on the start of the last line and rewrite it.

Something like:

Console.WriteLine(dir);
Console.SetCursorPosition(0, Console.CursorTop - 1);

EDIT:

According to your comment, you could do as follows:

Console.WriteLine("Searching file in...");
foreach (var dir in DirList)
{
    ClearCurrentConsoleLine();
    Console.Write(dir);
}

With ClearCurrentConsoleLine defined as:

public static void ClearCurrentConsoleLine()
{
    int currentLineCursor = Console.CursorTop;
    Console.SetCursorPosition(0, Console.CursorTop);
    for (int i = 0; i < Console.WindowWidth; i++)
        Console.Write(" ");
    Console.SetCursorPosition(0, currentLineCursor);
}