【问题标题】:Increase buffer for Console.Readline?增加 Console.Readline 的缓冲区?
【发布时间】:2015-01-30 21:36:22
【问题描述】:

我有一行大约 1.5kb 的文本。我希望我的控制台应用程序可以读取它,但只能粘贴前 255 个字符。如何增加此限制?我实际上是在 Visual Studio 2013 下的调试模式下使用 Console.ReadLine() 阅读它

【问题讨论】:

  • MSDN 中搜索 Console.Readline 这个评论“要阅读更长的行,调用 OpenStandardInput(Int32) 方法”应该会引导您到 OpenStandardInput
  • 我会接受这个答案。我写了using (var r = new StreamReader(Console.OpenStandardInput(2048))) { myvar = r.ReadLine(); } 它运行良好。我以为答案会在 app.config 或 Console.IncreaseBuffer(size) 之类的。
  • 我没有检查原因,但我的最后一条评论似乎有问题。它没有拿起整行。

标签: .net console.readline


【解决方案1】:

来自MSDN 这样的事情应该可以工作:

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

您可以将字节数组转换为字符串,例如:

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

【讨论】:

  • 好答案。没看MSDN;默认情况下,我会尽可能多地使用。
【解决方案2】:

这已经讨论过几次了。让我向您介绍迄今为止我看到的最佳解决方案(Console.ReadLine() max length?

概念:使用 OpenStandartInput 验证 readline 函数(就像提到的 cmets 中的人一样):

实现

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
}

通过这种方式,您可以从控制台中获得最大的收益,并且它可以工作超过 1.5 KB。

【讨论】:

  • 这段代码有一个问题。它包含行尾字符,因此它实际上破坏了我的代码,直到我输入 .Trim()
  • 哦,我明白了。 CF/EF,是的。抱歉我没注意,祝你的程序好运(:@acidzombie24
猜你喜欢
  • 2011-11-04
  • 2016-07-20
  • 2013-05-04
  • 2019-08-06
  • 2014-11-21
  • 2014-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多