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);
5 Answers 5
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));
This seems to wrap to a new line for me. How about Console.Write(new String(‘ ‘, Console.BufferWidth — 1)) ??
sure it does. it simply writes the complete line! Just move up one line afterwards. If you do -1, you will leave one character unblanked!
Once the last space of a console buffer row is used, the console cursor automatically jumps to the next line.
- Reset cursor back to the beginning before it reaches edge of console
- Erase old console output, placing cursor on next line
- 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(' ', Console.BufferWidth).ToArray()); Console.SetCursorPosition(0, Console.CursorTop - 1); > if (Console.KeyAvailable) break; >
(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.
Console. Clear Method
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Clears the console buffer and corresponding console window of display information.
[System.Runtime.Versioning.UnsupportedOSPlatform("android")] [System.Runtime.Versioning.UnsupportedOSPlatform("ios")] [System.Runtime.Versioning.UnsupportedOSPlatform("tvos")] public static void Clear ();
static member Clear : unit -> unit
[] [] [] static member Clear : unit -> unit
Exceptions
Examples
The following example uses the Clear method to clear the console before it executes a loop, prompts the user to select a foreground and background color and to enter a string to display. If the user chooses not to exit the program, the console’s original foreground and background colors are restored and the Clear method is called again before re-executing the loop.
using System; public class Example < public static void Main() < // Save colors so they can be restored when use finishes input. ConsoleColor dftForeColor = Console.ForegroundColor; ConsoleColor dftBackColor = Console.BackgroundColor; bool continueFlag = true; Console.Clear(); do < ConsoleColor newForeColor = ConsoleColor.White; ConsoleColor newBackColor = ConsoleColor.Black; Char foreColorSelection = GetKeyPress("Select Text Color (B for Blue, R for Red, Y for Yellow): ", new Char[] < 'B', 'R', 'Y' >); switch (foreColorSelection) < case 'B': case 'b': newForeColor = ConsoleColor.DarkBlue; break; case 'R': case 'r': newForeColor = ConsoleColor.DarkRed; break; case 'Y': case 'y': newForeColor = ConsoleColor.DarkYellow; break; >Char backColorSelection = GetKeyPress("Select Background Color (W for White, G for Green, M for Magenta): ", new Char[] < 'W', 'G', 'M' >); switch (backColorSelection) < case 'W': case 'w': newBackColor = ConsoleColor.White; break; case 'G': case 'g': newBackColor = ConsoleColor.Green; break; case 'M': case 'm': newBackColor = ConsoleColor.Magenta; break; >Console.WriteLine(); Console.Write("Enter a message to display: "); String textToDisplay = Console.ReadLine(); Console.WriteLine(); Console.ForegroundColor = newForeColor; Console.BackgroundColor = newBackColor; Console.WriteLine(textToDisplay); Console.WriteLine(); if (Char.ToUpper(GetKeyPress("Display another message (Y/N): ", new Char[] < 'Y', 'N' >)) == 'N') continueFlag = false; // Restore the default settings and clear the screen. Console.ForegroundColor = dftForeColor; Console.BackgroundColor = dftBackColor; Console.Clear(); > while (continueFlag); > private static Char GetKeyPress(String msg, Char[] validChars) < ConsoleKeyInfo keyPressed; bool valid = false; Console.WriteLine(); do < Console.Write(msg); keyPressed = Console.ReadKey(); Console.WriteLine(); if (Array.Exists(validChars, ch =>ch.Equals(Char.ToUpper(keyPressed.KeyChar)))) valid = true; > while (! valid); return keyPressed.KeyChar; > >
open System let getKeyPress msg validChars = Console.WriteLine() let mutable valid = false let mutable keyChar = ' ' while not valid do printfn "%s" msg let keyPressed = Console.ReadKey() printfn "" if validChars |> List.exists (fun ch -> ch.Equals(Char.ToUpper keyPressed.KeyChar)) then valid ConsoleColor.DarkBlue | 'R' | 'r' -> ConsoleColor.DarkRed | 'Y' | 'y' -> ConsoleColor.DarkYellow | _ -> ConsoleColor.White let backColorSelection = getKeyPress "Select Background Color (W for White, G for Green, M for Magenta): " [ 'W'; 'G'; 'M' ] let newBackColor = match backColorSelection with | 'W' | 'w' -> ConsoleColor.White | 'G' | 'g' -> ConsoleColor.Green | 'M' | 'm' -> ConsoleColor.Magenta | _ -> ConsoleColor.Black printfn "" printf "Enter a message to display: " let textToDisplay = Console.ReadLine() printfn "" Console.ForegroundColor
Module Example Public Sub Main() ' Save colors so they can be restored when use finishes input. Dim dftForeColor As ConsoleColor = Console.ForegroundColor Dim dftBackColor As ConsoleColor = Console.BackgroundColor Dim continueFlag As Boolean = True Console.Clear() Do Dim newForeColor As ConsoleColor Dim newBackColor As ConsoleColor Dim foreColorSelection As Char = GetKeyPress("Select Text Color (B for Blue, R for Red, Y for Yellow): ", < "B"c, "R"c, "Y"c >) Select Case foreColorSelection Case "B"c, "b"c newForeColor = ConsoleColor.DarkBlue Case "R"c, "r"c newForeColor = ConsoleColor.DarkRed Case "Y"c, "y"c newForeColor = ConsoleColor.DarkYellow End Select Dim backColorSelection As Char = GetKeyPress("Select Background Color (W for White, G for Green, M for Magenta): ", < "W"c, "G"c, "M"c >) Select Case backColorSelection Case "W"c, "w"c newBackColor = ConsoleColor.White Case "G"c, "g"c newBackColor = ConsoleColor.Green Case "M"c, "m"c newBackColor = ConsoleColor.Magenta End Select Console.WriteLine() Console.Write("Enter a message to display: ") Dim textToDisplay As String = Console.ReadLine() Console.WriteLine() Console.ForegroundColor = newForeColor Console.BackgroundColor = newBackColor Console.WriteLine(textToDisplay) Console.WriteLine() If Char.ToUpper(GetKeyPress("Display another message (Y/N): ", < "Y"c, "N"c >)) = "N" Then continueFlag = False End If ' Restore the default settings and clear the screen. Console.ForegroundColor = dftForeColor Console.BackgroundColor = dftBackColor Console.Clear() Loop While continueFlag End Sub Private Function GetKeyPress(msg As String, validChars() As Char) As Char Dim keyPressed As ConsoleKeyInfo Dim valid As Boolean = False Console.WriteLine() Do Console.Write(msg) keyPressed = Console.ReadKey() Console.WriteLine() If Array.Exists(validChars, Function(ch As Char) ch.Equals(Char.ToUpper(keypressed.KeyChar))) valid = True End If Loop While Not valid Return keyPressed.KeyChar End Function End Module
The example relies on a GetKeyPress method to validate the user's selection of a foreground and background color.
This example demonstrates the CursorLeft and CursorTop properties, and the SetCursorPosition and Clear methods. The example positions the cursor, which determines where the next write will occur, to draw a 5 character by 5 character rectangle using a combination of "+", "|", and "-" strings. Note that the rectangle could be drawn with fewer steps using a combination of other strings.
// This example demonstrates the // Console.CursorLeft and // Console.CursorTop properties, and the // Console.SetCursorPosition and // Console.Clear methods. using namespace System; int origRow; int origCol; void WriteAt( String^ s, int x, int y ) < try < Console::SetCursorPosition( origCol + x, origRow + y ); Console::Write( s ); >catch ( ArgumentOutOfRangeException^ e ) < Console::Clear(); Console::WriteLine( e->Message ); > > int main() < // Clear the screen, then save the top and left coordinates. Console::Clear(); origRow = Console::CursorTop; origCol = Console::CursorLeft; // Draw the left side of a 5x5 rectangle, from top to bottom. WriteAt( "+", 0, 0 ); WriteAt( "|", 0, 1 ); WriteAt( "|", 0, 2 ); WriteAt( "|", 0, 3 ); WriteAt( "+", 0, 4 ); // Draw the bottom side, from left to right. WriteAt( "-", 1, 4 ); // shortcut: WriteAt("---", 1, 4) WriteAt( "-", 2, 4 ); // . WriteAt( "-", 3, 4 ); // . WriteAt( "+", 4, 4 ); // Draw the right side, from bottom to top. WriteAt( "|", 4, 3 ); WriteAt( "|", 4, 2 ); WriteAt( "|", 4, 1 ); WriteAt( "+", 4, 0 ); // Draw the top side, from right to left. WriteAt( "-", 3, 0 ); // shortcut: WriteAt("---", 1, 0) WriteAt( "-", 2, 0 ); // . WriteAt( "-", 1, 0 ); // . // WriteAt( "All done!", 0, 6 ); Console::WriteLine(); >/* This example produces the following results: +---+ | | | | | | +---+ All done! */
// This example demonstrates the // Console.CursorLeft and // Console.CursorTop properties, and the // Console.SetCursorPosition and // Console.Clear methods. using System; class Sample < protected static int origRow; protected static int origCol; protected static void WriteAt(string s, int x, int y) < try < Console.SetCursorPosition(origCol+x, origRow+y); Console.Write(s); >catch (ArgumentOutOfRangeException e) < Console.Clear(); Console.WriteLine(e.Message); >> public static void Main() < // Clear the screen, then save the top and left coordinates. Console.Clear(); origRow = Console.CursorTop; origCol = Console.CursorLeft; // Draw the left side of a 5x5 rectangle, from top to bottom. WriteAt("+", 0, 0); WriteAt("|", 0, 1); WriteAt("|", 0, 2); WriteAt("|", 0, 3); WriteAt("+", 0, 4); // Draw the bottom side, from left to right. WriteAt("-", 1, 4); // shortcut: WriteAt("---", 1, 4) WriteAt("-", 2, 4); // . WriteAt("-", 3, 4); // . WriteAt("+", 4, 4); // Draw the right side, from bottom to top. WriteAt("|", 4, 3); WriteAt("|", 4, 2); WriteAt("|", 4, 1); WriteAt("+", 4, 0); // Draw the top side, from right to left. WriteAt("-", 3, 0); // shortcut: WriteAt("---", 1, 0) WriteAt("-", 2, 0); // . WriteAt("-", 1, 0); // . // WriteAt("All done!", 0, 6); Console.WriteLine(); >> /* This example produces the following results: +---+ | | | | | | +---+ All done! */
// This example demonstrates the // Console.CursorLeft and // Console.CursorTop properties, and the // Console.SetCursorPosition and // Console.Clear methods. open System // Clear the screen, then save the top and left coordinates. Console.Clear() let origRow = Console.CursorTop let origCol = Console.CursorLeft let writeAt s x y = try Console.SetCursorPosition(origCol + x, origRow + y) printfn $"%s" with :? ArgumentOutOfRangeException as e -> Console.Clear() printfn $"" // Draw the left side of a 5x5 rectangle, from top to bottom. writeAt "+" 0 0 writeAt "|" 0 1 writeAt "|" 0 2 writeAt "|" 0 3 writeAt "+" 0 4 // Draw the bottom side, from left to right. writeAt "-" 1 4 // shortcut: writeAt "---", 1, 4) writeAt "-" 2 4 // . writeAt "-" 3 4 // . writeAt "+" 4 4 // Draw the right side, from bottom to top. writeAt "|" 4 3 writeAt "|" 4 2 writeAt "|" 4 1 writeAt "+" 4 0 // Draw the top side, from right to left. writeAt "-" 3 0 // shortcut: writeAt "---", 1, 0) writeAt "-" 2 0 // . writeAt "-" 1 0 // . writeAt "All done!" 0 6 printfn "" // This example produces the following results: // // +---+ // | | // | | // | | // +---+ // // All done!
' This example demonstrates the ' Console.CursorLeft and ' Console.CursorTop properties, and the ' Console.SetCursorPosition and ' Console.Clear methods. Class Sample Protected Shared origRow As Integer Protected Shared origCol As Integer Protected Shared Sub WriteAt(s As String, x As Integer, y As Integer) Try Console.SetCursorPosition(origCol + x, origRow + y) Console.Write(s) Catch e As ArgumentOutOfRangeException Console.Clear() Console.WriteLine(e.Message) End Try End Sub Public Shared Sub Main() ' Clear the screen, then save the top and left coordinates. Console.Clear() origRow = Console.CursorTop origCol = Console.CursorLeft ' Draw the left side of a 5x5 rectangle, from top to bottom. WriteAt("+", 0, 0) WriteAt("|", 0, 1) WriteAt("|", 0, 2) WriteAt("|", 0, 3) WriteAt("+", 0, 4) ' Draw the bottom side, from left to right. WriteAt("-", 1, 4) ' shortcut: WriteAt("---", 1, 4) WriteAt("-", 2, 4) ' . WriteAt("-", 3, 4) ' . WriteAt("+", 4, 4) ' Draw the right side, from bottom to top. WriteAt("|", 4, 3) WriteAt("|", 4, 2) WriteAt("|", 4, 1) WriteAt("+", 4, 0) ' Draw the top side, from right to left. WriteAt("-", 3, 0) ' shortcut: WriteAt("---", 1, 0) WriteAt("-", 2, 0) ' . WriteAt("-", 1, 0) ' . ' WriteAt("All done!", 0, 6) Console.WriteLine() End Sub End Class ' 'This example produces the following results: ' '+---+ '| | '| | '| | '+---+ ' 'All done! '
Remarks
Using the Clear method is equivalent invoking the MS-DOS cls command in the command prompt window. When the Clear method is called, the cursor automatically scrolls to the top-left corner of the window and the contents of the screen buffer are set to blanks using the current foreground background colors.
Attempting to call the Clear method when a console application's output is redirected to a file throws a IOException. To prevent this, always wrap a call to the Clear method in a try … catch block.
How to clear the Console in c#.net?
Just that. I found a similar question here : c# console, Console.Clear problem but that didn't answer the question. UPDATES : Console.Clear() throws : IOException (The handle is invalid) The app is a WPF app. Writing to the console however is no problem at all, nor is reading from.
Just a kind of playgarden, it's my program to do tests. I only use the wpfstuff when I'm testing out wpf, otherwise I just print to the console, by coincidence, i wanted to clear the console, never thought i wouldn't work. Of course I can start a console app without that prob, but I want to be able to do that in wpf in the future, or, at least, grasp the problem.
7 Answers 7
Console.Clear() works in a console application.
When Calling Console.Clear() in a ASP.NET web site project or in a windows forms application, then you'll get the IOException.
What kind of application do you have?
I'm not sure if this will help, but as you can read in this forum thread, Console.Clear() throws an IOException if the console output is being redirected. Maybe this is the case for WPF applications? The article describes how to check whether the console is being redirected.
It's a wpf test app. Indeed, when trying helloWorld kinda stuff in consoleApp, I don't have a problem.
Are you trying this method on a non-Console application? If so that would explain the error. Other types of applications, ASP.Net projects, WinForms, etc . don't actually create a console for writing. So the Clear has nothing to operate on and throws an exception.
Console.Clear() - this is the equivalent of the "cls" command.
Try Console.Clear() - it has been available since .NET 2.0.
Console.Clear() will do the trick. It should not throw an IOException. If it is, there's something else going on that you're not telling us, in which case you should show us some code.
Martin suggested the error appears in winforms or Asp net. This is wpf and could be a problem too I guess, but even then, the question stands (I can use the console to write to and read from after all)
Are you using some artificial means, like what is described here to display a console window? I tried creating a WPF application then changing the application output type in its properties Project-> Properties. to Console Application. Once I did that a console window popped up when I started my application and I could write to it and call Console.Clear() without any exceptions. (the basic idea is explained here, although my properties UI was slightly different than what is described)
Do you really need to clear it? You could also create your own "cls" command that prints out a 100 blank lines to the console and makes it "appear" to have cleared. just an idea.