简体   繁体   English

如何解决C#中的OutOfMemory异常?

[英]How to get around OutOfMemory exception in C#?

I've got a few huge xml files, 1+ gb. 我有一些巨大的xml文件,1 + gb。 I need to do some filtering operations with them. 我需要对它们进行一些过滤操作。 The easiest idea I've come up with is to save them as txt and ReadAllText from them, and start doing some operations like 我提出的最简单的想法是将它们保存为txt和ReadAllText,并开始执行一些操作,如

  var a = File.ReadAllText("file path");
  a = a.Replace("<", "\r\n<");

The moment I try to do that, however, the program crashes out of memory. 然而,在我尝试这样做的那一刻,程序崩溃了内存。 I've looked at my task manager while I run it and the RAM usage climbs to 50% and the moment it reaches it the program dies. 我在运行它时看着我的任务管理器,RAM使用率上升到50%,当它达到它时,程序就会死掉。

Does anyone have any ideas on how I operate with this file avoiding the OutOfMemory exception or allow the program to pull on more of the memory. 有没有人对我如何操作这个文件有任何想法,避免OutOfMemory异常或允许程序提取更多的内存。

If you can do it line by line, instead of saying "Read everything to memory" with File.ReadAllText , you can say "Yield me one line at time" with File.ReadLines . 如果你能做到这一点一行行,而不是说“阅读一切记忆”着, File.ReadAllText ,你可以说“屈服我一条线在时间”与File.ReadLines

This will return IEnumerable which uses deferred execution. 这将返回使用延迟执行的IEnumerable。 You can do it like this: 你可以这样做:

using(StreamWriter sw = new StreamWriter(newFilePath))
foreach(var line in File.ReadLines(path))
{
    sw.WriteLine(line.Replace("<", "\r\n<"));
    sw.Flush();
}

If you want to learn more about deferred execution, you can check this github page. 如果您想了解有关延迟执行的更多信息,可以查看 github页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM