Clears the console buffer and corresponding console window of display information.
Assembly: mscorlib (in mscorlib.dll)
Using the method is equivalent invoking the MS-DOS cls command in the command prompt window. When the 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 method when a console application's output is redirected to a file throws a IOException. To prevent this, always wrap a call to the method in a try…catch block.
The following example uses the 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 method is called again before re-executing the loop.
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 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.
Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.