How to Get User Input and allowing more than 256 characters to be entered on .NET Console Application

Posted by Daniel - 40,199 Views

readlineConsole Application is good if you want to perform processes without the need of user intervention. Usually automated processes designed to run on schedule. But you can also prompt the user for action if for some reasons you need to do it and it is very simple. All you need to do is utilize the Console.ReadLine command.

This how to article will show you an example of it. The scenario applied in the included demo project is how to prompt the user for keyboard input and how to extend the 256 characters limit. That’s why you see two related processes in the title of this post.

GET USER INPUT. As I said before it’s very simple to get the user input. Declare a string variable then assign Console.ReadLine command to it as shown below:

Dim strInput As String
strInput = Console.ReadLine()

When executed, the application will prompt the user for keyboard input. After the user hit the [Enter] key, the strInput variable will contain characters typed by the user.

Unfortunately, the default limit of characters allowed to be entered is 256 characters. It’s quite reasonable since most of console applications are not designed to handle large amount of user input at a time, but if somehow you need to get more than that limit, following is the trick:

ALLOWING MORE THAN 256 CHARACTERS. The logic is simple. Specify the limit of characters allowed to be entered by the user before calling the Console.ReadLine command. Below are the implementations,

VB.Net Code:

Dim inputBuffer(1024) As Byte
Dim inputStream As Stream = Console.OpenStandardInput(inputBuffer.Length)
Console.SetIn(New StreamReader(inputStream))
strInput = Console.ReadLine()

C# Code

byte[] inputBuffer = new byte[1024];
Stream inputStream = Console.OpenStandardInput(inputBuffer.Length);
Console.SetIn(new StreamReader(inputStream));
string strInput = Console.ReadLine();

Tips: Just in case you have no idea how to do it , to paste text into the command prompt window you can right click the caption then select [Edit] - [Paste].

Download ReadLine Example (60 KB)

share this article

Digg del.icio.us Netscape StumbleUpon Yahoo! MyWeb reddit Furl Magnolia Newsvine Technorati SlashDot Blinklist Simpy Google
This post as PDFPosted in: Programming - March 2008 | raw