【问题标题】:Large File - Adding Lines - Out Of Memory大文件 - 添加行 - 内存不足
【发布时间】:2015-02-04 10:54:29
【问题描述】:

我有一个非常大的 sql 插入文件,在 SQL 企业管理器中运行它时会引发“内存不足”错误。

我看到的建议是在插入的每 X 行中添加“GO”命令是“批处理”的。

我正在尝试编写一个小函数来读取文件,每 50 行添加一行文本“GO”

我编写的代码在运行时也抛出 System.OutOfMemoryException。

谁能建议一个更好的方法来编写我的代码来解决这个问题?

这是我写的:

public static void AddGo()
    {
        int currentline = 0;

        string FilePath = @"C:\Users\trevo_000\Desktop\fmm89386.sql";

        var text = new StringBuilder();

        foreach (string s in File.ReadAllLines(FilePath))
        {
            // add the current line
            text.AppendLine(s);

            // increase the line counter
            currentline += 1;

            if (currentline == 50)
            {
                text.AppendLine("GO");
                currentline = 0;
            }
        }

        using (var file = new StreamWriter(File.Create(@"C:\Users\trevo_000\Desktop\fmm89386Clean.sql")))
        {
            file.Write(text.ToString());
        }

    }

【问题讨论】:

  • 使用ReadLines 而不是ReadAllLines 并在你正在阅读的同一个循环中进行写入,而不是使用StringBuilder。这样一来,您一次不需要在内存中保留超过一行。
  • 你的目标是什么?插入大量行?为什么是文件?不能使用 SqlCommand 吗?还是批量导入?
  • 或者,您可以在具有足够 RAM 的计算机上使用 64 位构建的应用程序,并决定不值得为一次性脚本优化内存使用。

标签: c#


【解决方案1】:

您将文件保存在内存中,然后将其从内存写入文件。而不是在处理输入文件时写入输出文件;这种事:

public static void AddGo() {
    int currentline = 0;

    string inputFilePath = @"C:\Users\trevo_000\Desktop\fmm89386.sql";
    string outputFilePath = @"C:\Users\trevo_000\Desktop\fmm89386Clean.sql";
    using (var outputFileStream=File.CreateText(outputFilePath)) {
        foreach (string s in File.ReadLines(inputFilePath))
        {
            // add the current line
            outputFileStream.WriteLine(s);

            // increase the line counter
            currentline += 1;

            if (currentline == 50)
            {
                outputFileStream.WriteLine("GO");
                currentline = 0;
            }
        }
    }
}

注意在输入文件中使用 ReadLines,而不是 ReadAllLines - 请参阅 What is the difference between File.ReadLines() and File.ReadAllLines()? 了解更多信息。

【讨论】:

    猜你喜欢
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2019-02-19
    • 2016-03-23
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多