-1

So i have big Text file that i want to read and take specific block (about 30 lines). This block exist many times in my text file and i want to take the last.

So this is what i have try:

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);
            }

This Text file changed every 20 second so i am doing this with while loop and i need to write the last block on new Text file.

The problem here that after the first time (that works fine) i got an error: OutOfMemoryException

EDIT

I try another approach and read line by line but the result was the same.

MasterMastic
  • 20,711
  • 12
  • 68
  • 90
Erofh Tor
  • 159
  • 1
  • 8
  • Wouldn't reading the file starting from somewhere near the end work? https://stackoverflow.com/questions/4368857/read-from-a-file-starting-at-the-end-similar-to-tail – Andy Apr 22 '18 at 09:59
  • But i cannot be sure that my block is there – Erofh Tor Apr 22 '18 at 10:01
  • Project > Properties > Build tab > untick the "Prefer 32-bit" checkbox. You don't prefer it. Or write smarter code by reading the file one line at a time. Or acknowledge that a text file makes for a truly miserable database and move the data into a dbase table. – Hans Passant Apr 22 '18 at 13:08

1 Answers1

0

Use a StreamWriter to directly write each line you generate into the textfile. This avoids storing the whole long file in memory first.

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());
        }
    }
Vietvo
  • 91
  • 7
  • But i already have the text file that i am read from so what is the different ? – Erofh Tor Apr 22 '18 at 12:36
  • OutOfMemoryException occurs when you call File.WriteAllText too many times, try to use StreamWriter to write out your data – Vietvo Apr 22 '18 at 12:43