c# - 逐行读取约 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
我不明白为什么 - 我之前加载了更大尺寸的文件。
解决方案
这是一个科学怪人的行动好吧。这是一种更简单的逐行阅读文本的方法:
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
推荐阅读
- c# - .equals() 和 == C# 的混淆?
- python - `multiprocessing` `starmap_async` 只调用一次回调?
- javascript - 如何仅在数组javascript中使用“forEach”函数列出项目
- rgraph - RGraph V5 升级 - 获取上下文时出错
- php - 使用迭代返回 for 循环的结果
- android - 为什么我的 android 选项卡布局不起作用?
- azure - 如何在 kubernetes 中从 Angular 应用程序调用 .net core web api
- algorithm - 装袋分类器(平均)如何工作?
- c# - C#相同输入的不同结果
- c++ - 如何使用基于范围的 for 循环迭代器?