我正在尝试根据某个字符的存在来计算大文件中的行数,并希望使用StreamReader和ReadBlock - 下面是我的代码。
protected virtual long CalculateRowCount(FileStream inStream, int bufferSize)
{
long rowCount=0;
String line;
inStream.Position = 0;
TextReader reader = new StreamReader(inStream);
char[] block = new char[4096];
const int blockSize = 4096;
int indexer = 0;
int charsRead = 0;
long numberOfLines = 0;
int count = 1;
do
{
charsRead = reader.ReadBlock(block, indexer, block.Length * count);
indexer += blockSize ;
numberOfLines = numberOfLines + string.Join("", block).Split(new string[] { "&ENDE" }, StringSplitOptions.None).Length;
count ++;
} while (charsRead == block.Length);//charsRead !=0
reader.Close();
fileRowCount = rowCount;
return rowCount;
}
但我收到错误
偏移量和长度超出数组的范围,或者计数大于从索引到源集合末尾的元素数。
我不确定有什么问题......你能帮忙吗?谢谢你!
答案 0 :(得分:3)
首先,仔细阅读StreamReader.ReadBlock()文档http://msdn.microsoft.com/en-us/library/system.io.streamreader.readblock.aspx并与您正在做的事情进行比较: