Increase buffer for Console.Readline?

2019-09-14 05:04发布

问题:

I have a line that is about 1.5kb of text. I want my console app to read it but only the first 255 characters can be pasted in. How do I increase this limit? I am literally reading it using Console.ReadLine() in debug mode under visual studio 2013

回答1:

From MSDN something like this ought to work:

Stream inputStream = Console.OpenStandardInput();
byte[] bytes = new byte[1536];    // 1.5kb
int outputLength = inputStream.Read(bytes, 0, 1536);

The you can convert your byte array to a string with something like:

var myStr = System.Text.Encoding.UTF8.GetString(bytes);


回答2:

This have been already discussed a couple times. Let me introduce you to the best solution i saw so far ( Console.ReadLine() max length? )

The concept: verriding the readline function with OpenStandartInput (like the guys in the comments mentioned):

The implementation:

private static string ReadLine()
{
    Stream inputStream = Console.OpenStandardInput(READLINE_BUFFER_SIZE); // declaring a new stream to read data, max readline size
    byte[] bytes = new byte[READLINE_BUFFER_SIZE]; // defining array with the max size
    int outputLength = inputStream.Read(bytes, 0, READLINE_BUFFER_SIZE); //reading
    //Console.WriteLine(outputLength); - just for checking the function
    char[] chars = Encoding.UTF7.GetChars(bytes, 0, outputLength); // casting it to a string
    return new string(chars); // returning
}

This way you get the most you can from the console, and it'll work for more than 1.5 KB.