c# - ASP.net C# : How to read 20 to 200 GB file line by line using File. ReadLines(文件名).GetEnumerator()?

标签 c# asp.net

我们正在尝试使用以下代码。

 public static int SplitFile(string fileName, string tmpFolder, List<string> queue, int splitSize = 100000)
    {
        int chunk = 0;
        if (!Directory.Exists(tmpFolder))
            Directory.CreateDirectory(tmpFolder);
        using (var lineIterator = File.ReadLines(fileName).GetEnumerator())
        {
            bool stillGoing = true;
            for (chunk = 0; stillGoing; chunk++)
            {
                stillGoing = WriteChunk(lineIterator, splitSize, chunk, tmpFolder, queue);
            }
        }
        return chunk;
    }

    private static bool WriteChunk(IEnumerator<string> lineIterator,
                                   int splitSize, int chunk, string tmpFolder, List<string> queue)
    {
        try
        {

            //int tmpChunkSize = 1000;
            //int tmpChunkInc = 0;
            string splitFile = Path.Combine(tmpFolder, "file" + chunk + ".txt");

            using (var writer = File.CreateText(splitFile))
            {
                queue.Add(splitFile);
                for (int i = 0; i < splitSize; i++)
                {
                    if (!lineIterator.MoveNext())
                    {
                        return false;
                    }
                    writer.WriteLine(lineIterator.Current);

                }
            }

            return true;
        }
        catch (Exception)
        {

            throw;
        }

    }

它创建了大约 36 个文本文件(大约 800 MB),但在 lineIterator.MoveNext() 中创建第 37 个文件时开始抛出“内存不足异常”。

虽然 lineIterator.Current 在调试器中显示了值。

最佳答案

由于这是一个巨大的文件,您应该读取它 Seek 和 BinaryReader 的 ReadBytes 方法。

可以看一个简单的例子here .使用 ReadBytes 检查最后的新行并在您读取的一定数量的行中写入过程文件后。不要把你读到的每一行都写下来,也不要把所有的数据都放在内存中。

剩下的就交给你了。

也许它与那个有关When does File.ReadLines free resources

IEnumerable doesn't inherit from IDisposable because typically, the class that implements it only gives you the promise of being enumerable, it hasn't actually done anything yet that warrants disposal.

关于c# - ASP.net C# : How to read 20 to 200 GB file line by line using File. ReadLines(文件名).GetEnumerator()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16898265/

相关文章:

c# - 如何结合RegularExpressionValidator控件和RequiredFieldValidator?

asp.net - 为什么融合不记录绑定(bind)错误?

c# - 我可以在一个程序集中同时使用 C# 和 C++/CLI 吗?

javascript - 已经在进行中时不允许 POST BACK

ASP.NET MVC、Linq to SQL 数据注释验证

c# - 在主页 Nopcommerce 上添加 block 标题以分隔产品

C# - 从程序集中获取资源字符串的最快方法

c# - 如何跟踪使用 WebClient 调用的原始 HTTP 请求?

c# - 带别名的 Linq

c# - 如何从 MVVM 中的 ViewModel 访问用户控件(工具栏)?