There's a big text file. And I cannot read it with File.ReadAllText()
method. How to read it piece by piece in C#?
Asked
Active
Viewed 1,078 times
-1

smwikipedia
- 61,609
- 92
- 309
- 482
-
1First of all is it a text file? If yes you can read the file line by line with a stream reader. See MSDN for streamreader and readline – MrSykkox Sep 15 '14 at 05:00
-
@paqogomez please be constructive. – smwikipedia Sep 15 '14 at 06:18
1 Answers
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