C# 仅从第二次读取文本 OutOfMemoryException



所以我有大Text文件,我想读取并获取特定的块(大约 30 行(。这个块在我的文本文件中存在很多次,我想采取最后一个。

所以这就是我尝试过的:

while (true)
            {
                Thread.Sleep(30000);
                string text = File.ReadAllText(@"c:file.txt");
                string table = string.Join("", text.Substring(text.LastIndexOf("My Statistics:"))
                    .Split(new[] { 'n' })
                    .Take(24)
                    .Select(i => i.ToString())
                    .ToArray());
                File.WriteAllText(@"last.txt", table);
            }

这个Text文件每 20 秒更改一次,所以我使用 while 循环执行此操作,我需要在新Text文件上写入最后一个块。

这里的问题是第一次(工作正常(后我得到一个错误:OutOfMemoryException

编辑

我尝试另一种方法并逐行阅读,但结果是一样的。

使用 StreamWriter 直接将生成的每一行写入文本文件中。这样可以避免先将整个长文件存储在内存中。

using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\Somewhere\whatever.txt")) 
    {
        //Generate all the single lines and write them directly into the file
        for (int i = 0; i<=10000;i++)
        {
            sw.WriteLine("This is is : " + i.ToString());
        }
    }

最新更新