【发布时间】:2014-09-15 04:55:14
【问题描述】:
有一个很大的文本文件。我无法用File.ReadAllText() 方法阅读它。如何在 C# 中逐段阅读?
【问题讨论】:
-
首先是文本文件吗?如果是,您可以使用流阅读器逐行读取文件。请参阅 MSDN 了解 streamreader 和 readline
-
@paqogomez 请保持建设性。
标签: c#
有一个很大的文本文件。我无法用File.ReadAllText() 方法阅读它。如何在 C# 中逐段阅读?
【问题讨论】:
标签: c#
试试这样的。
在这里,我以 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
}
}
【讨论】: