简体   繁体   English

File.ReadAllText OutOfMemoryException

[英]File.ReadAllText OutOfMemoryException

I have a large SQL script (around 70MB), and I need to read it all into memory, and then split on the GO statements. 我有一个大的SQL脚本(大约70MB),我需要将它全部读入内存,然后拆分GO语句。

I'm doing the following, but getting OutOfMemoryException : 我正在做以下,但得到OutOfMemoryException

var script = File.ReadAllText(scriptFile);
var scriptName = Path.GetFileName(scriptFile);
var commands = Regex.Split(script, "^GO\r\n", RegexOptions.Multiline | RegexOptions.IgnoreCase);

Then, for each script fragment in commands , I call ExecuteNonQuery . 然后,对于commands每个脚本片段,我调用ExecuteNonQuery This all works fine until I try to load this large script file. 这一切都正常,直到我尝试加载这个大型脚本文件。

Any suggestions for parsing that text file more efficiently? 有没有更有效地解析该文本文件的建议?

Try something like this 尝试这样的事情

public static IEnumerable<string> SplitScriptOnGo(string scriptPath)
{
    var buffer = new StringBuilder();
    foreach (var line in File.ReadLines(scriptPath))
    {
        if (line == "GO")
        {
            yield return buffer.ToString();
            buffer.Clear();
        }
        else
        {
            buffer.AppendLine(line);
        }
    }
}

That will read one line at a time, buffer them into a StringBuilder and then yield the buffer when it sees a "Go" line. 这将一次读取一行,将它们缓冲到StringBuilder ,然后在看到“Go”行时生成缓冲区。 As long as you don't ToList this you can iterate over the results and execute each SQL statement without reading the entire script into memory. 只要您没有ToList ,就可以迭代结果并执行每个SQL语句,而无需将整个脚本读入内存。

Does it fail on ReadAllText() or on Split()? 它是否在ReadAllText()或Split()上失败?

I don't know your system specs, but I doubt you have insufficient memory, my guess is it fails on Split() and something in your split is causing an infinite loop. 我不知道你的系统规格,但我怀疑你没有足够的内存,我的猜测是它在Split()上失败并且你的分裂中的某些东西导致无限循环。

Perhaps instead of reading everything at once you could simply read until the first "go", execute, then continue reading to next go, etc? 或许不是一次阅读所有内容,你可以简单地阅读直到第一个“去”,执行,然后继续阅读下一个去等等? Eventually it'll either process the whole file, or it'll fail (at which point you'll know which "GO" statement is causing the issues by looking at the string you just read in the debugger). 最终它要么处理整个文件,要么它将失败(此时你将通过查看你刚刚在调试器中读到的字符串知道哪个“GO”语句导致问题)。

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

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