首页 > 解决方案 > 逐行读取约 180KB 的文件会导致 StackOverflowException

问题描述

该文本文件有约 15,000 行短行。我是这样读的:

using (var reader = new StreamReader("words.txt")) {
    while (reader.Peek() >= 0) {
        list.Add(reader.ReadLine());
    }
    var r = new Random();
    var randomLineNumber = r.Next(0, list.Count - 1);
    InterfacePassword.Text = list[randomLineNumber].ToString();
}

它来自其他 SO 答案,我不确定它是否真的会做我想要的。不幸的是,它导致StackOverflowException我不明白为什么 - 我之前加载了更大尺寸的文件。

标签: c#

解决方案


这是一个科学怪人的行动好吧。这是一种更简单的逐行阅读文本的方法:

foreach (string line in File.ReadAllLines("words.txt"))
{
  // Do whatever with line
}

或者更适合您的情况:

string[] lines = File.ReadAllLines("words.txt");
InterfacePassword.Text = list[new Random().Next(0, lines.Length)];
// note that Next(..., max) is exclusive, no need to do -1

推荐阅读