【发布时间】:2015-04-05 16:42:11
【问题描述】:
我希望将 150 MB 的文本文件加载到字符串中。该文件是 UTF16 编码的,因此它将在内存中生成一个大约 150 MB 的字符串。我尝试过的所有方法都会导致 Out of Memory 异常。
我知道这是一个巨大的字符串,当然不是我想要的做事方式。但是,如果不对即将推出的应用程序进行大量真正深刻的更改,目前我真的无能为力。该文件中没有一组均匀分布的行。一行可以包含整个文件大小的 80% 左右。
这是我尝试过的:
方法一
// Both of these throw Out of Memory exception
var s = File.ReadAllText(path)
var s = File.ReadAllText(path, Encoding.Unicode);
方法二
var sb = new StringBuilder();
// I've also tried a few other iterations on this with other types of streams
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
// This throws an exception
sb.ToString();
方法3
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader sr = new StreamReader(fs, Encoding.Unicode))
{
int initialSize = (int)fs.Length / 2; // Comes to a value of 73285158 with my test file
var sb = new StringBuilder(initialSize); // This throws an exception
string line;
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
sb.ToString();
}
那么,我该怎么做才能将此文件加载到字符串变量中?
编辑:添加了基于 cmets 解决问题的额外尝试。
【问题讨论】:
-
作为附加措施,您可能希望强制使用 x64 而不是 AnyCPU/首选 x86... 32 位进程中的内存碎片是大型分配失败的常见原因。
-
不幸的是,这必须是一个 32 位应用程序。
-
便宜的方法来帮助stackoverflow.com/questions/14186256/…我已经将它用于图像,但更好地解决核心问题
-
如果您正在处理有限的资源,最好的方法可能是打开一个 FileStream 并使用流阅读器对其进行迭代。有点符合“你怎么吃大象?一次一口”的原则。 (双关语)
标签: c# string file-handling