How to read very long input from console in C#?

谁说我不能喝 提交于 2019-12-19 19:57:17

问题


I need to load veeeery long line from console in C#, up to 65000 chars. Console.ReadLine itself has a limit of 254 chars(+2 for escape sequences), but I can use this:

static string ReadLine()
{
    Stream inputStream = Console.OpenStandardInput(READLINE_BUFFER_SIZE);
    byte[] bytes = new byte[READLINE_BUFFER_SIZE];
    int outputLength = inputStream.Read(bytes, 0, READLINE_BUFFER_SIZE);
    Console.WriteLine(outputLength);
    char[] chars = Encoding.UTF7.GetChars(bytes, 0, outputLength);
    return new string(chars);
}

...to overcome that limit, for up to 8190 chars(+2 for escape sequences) - unfortunately I need to enter WAY bigger line, and when READLINE_BUFFER_SIZE is set to anything bigger than 8192, error "Not enough storage is available to process this command" shows up in VS. Buffer should be set to 65536. I've tried a couple of solutions to do that, yet I'm still learning and none exceeded either 1022 or 8190 chars, how can I increase that limit to 65536? Thanks in advance.


回答1:


try Console.Read with StringBuilder

        StringBuilder sb =new StringBuilder();
        while (true) {
            char ch = Convert.ToChar(Console.Read());
            sb.Append(ch);
            if (ch=='\n') {
                break;
            }
        }



回答2:


You have to add following line of code in your main() method:

byte[] inputBuffer = new byte[4096];
                Stream inputStream = Console.OpenStandardInput(inputBuffer.Length);
                Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length));

Then you can use Console.ReadLine(); to read long user input.




回答3:


I agree with Manmay, that seems to work for me, and I also attempt to keep the default stdin so I can restore it afterwards:

        if (dbModelStrPathname == @"con" ||
            dbModelStrPathname == @"con:")
        {
            var stdin = Console.In;

            var inputBuffer = new byte[262144];
            var inputStream = Console.OpenStandardInput(inputBuffer.Length);
            Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length));

            dbModelStr = Console.In.ReadLine();

            Console.SetIn(stdin);
        }
        else
        {
            dbModelStr = File.ReadAllText(dbModelStrPathname);
        }


来源:https://stackoverflow.com/questions/9750853/how-to-read-very-long-input-from-console-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!