有一个大文本文件。我无法用File.ReadAllText()
方法阅读它。如何在C#中逐一阅读?
答案 0 :(得分:3)
尝试这样的事情。
这里我以2兆字节的块读取文件。
这将减少加载文件和读取的负载,因为它读取的块为2兆字节。
如果您需要,可以将大小从2兆字节改为大小。
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
}
}