如何使用 StreamReader 读取非常大的文本文件?
我想读取一个巨大的 .txt 文件,但由于其大小过大,导致内存溢出。
有什么帮助吗?
private void button1_Click(object sender, EventArgs e)
{
using (var Reader = new StreamReader(@"C:\Test.txt"))
{
textBox1.Text += Reader.ReadLine();
}
}
文本文件就是:
Line1
Line2
Line3
字面意思就是这样。
我想将文本文件按原样加载到多行文本框,100% 复制。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,您发布的代码只会将文件的第一行放入
TextBox
中。你想要的是这样的:现在对于
OutOfMemoryException
:我还没有测试过这个,但是你是否尝试过TextBox.AppendText
方法而不是使用+= ?后者肯定会分配大量字符串,当您接近文件末尾时,其中大多数字符串将接近整个文件的长度。
据我所知,
AppendText
也可以这样做;但它的存在让我怀疑它是为了处理这种情况而放在那里的。我可能是错的——就像我说的,还没有亲自测试过。Firstly, the code you posted will only put the first line of the file into the
TextBox
. What you want is this:Now as for the
OutOfMemoryException
: I haven't tested this, but have you tried theTextBox.AppendText
method instead of using+=
? The latter will certainly be allocating a ton of strings, most of which are going to be nearly the length of the entire file by the time you near the end of the file.For all I know,
AppendText
does this as well; but its existence leads me to suspect it's put there to deal with this scenario. I could be wrong -- like I said, haven't tested personally.通过以下操作,您将获得更快的性能:
它还可能有助于解决内存问题,因为在读取每一行时连续分配更大的字符串会浪费大量内存。
诚然,GC 应该在您看到 OutOfMemoryException 之前收集较旧的字符串,但无论如何我都会尝试上述操作。
You'll get much faster performance with the following:
It might also help with your memory problem, since you're wasting an enormous amount of memory by allocating successively larger strings with each line read.
Granted, the GC should be collecting the older strings before you see an
OutOfMemoryException
, but I'd give the above a shot anyway.首先使用富文本框而不是常规文本框。它们更适合您正在使用的大量数据。但是您仍然需要读取数据。
First use a rich text box instead of a regular text box. They're much better equiped for the large amounts of data you're using. However you still need to read the data in.
一次一行地读取并处理它,或者将其分成块并单独处理块。您还可以向我们展示您拥有的代码,并告诉我们您想用它来完成什么任务。
下面是一个示例:C# 读取包含由制表符分隔的数据的文本文件 请注意
ReadLine()
和WriteLine()
语句。TextBox 受到它可以容纳的字符数的严重限制。您可以尝试在 AppendText() 方法改为 ="nofollow noreferrer">
RichTextBox
。Read and process it one line at a time, or break it into chunks and deal with the chunks individually. You can also show us the code you have, and tell us what you are trying to accomplish with it.
Here is an example: C# Read Text File Containing Data Delimited By Tabs Notice the
ReadLine()
andWriteLine()
statements.TextBox is severely limited by the number of characters it can hold. You can try using the
AppendText()
method on aRichTextBox
instead.