-1

There's a big text file. And I cannot read it with File.ReadAllText() method. How to read it piece by piece in C#?

smwikipedia
  • 61,609
  • 92
  • 309
  • 482

1 Answers1

3

Try Something like this.

Here i read the file in blocks of 2 megabytes.

This will reduce the load of loading file and reading as it reads in block of 2 megabytes.

You can change the size if you want from 2 megabytes to what so ever.

using (Stream objStream = File.OpenRead(FilePath))
{
    // Read data from file
    byte[] arrData = { };

    // Read data from file until read position is not equals to length of file
    while (objStream.Position != objStream.Length)
    {
        // Read number of remaining bytes to read
        long lRemainingBytes = objStream.Length - objStream.Position;

        // If bytes to read greater than 2 mega bytes size create array of 2 mega bytes
        // Else create array of remaining bytes
        if (lRemainingBytes > 262144)
        {
            arrData = new byte[262144];
        }
        else
        {
            arrData = new byte[lRemainingBytes];
        }

        // Read data from file
        objStream.Read(arrData, 0, arrData.Length);

        // Other code whatever you want to deal with read data
   }
}
Nirav Kamani
  • 3,192
  • 7
  • 39
  • 68