【问题标题】:ArgumentException while reading using readblock streamreader使用 readblock streamreader 读取时出现 ArgumentException
【发布时间】:2014-10-27 04:28:45
【问题描述】:

我正在尝试根据某个字符的存在来计算大文件的行数,并希望使用 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;

        }

但我得到错误

数组的偏移量和长度超出范围或计数大于从索引到源集合末尾的元素数。

我不确定出了什么问题...你能帮忙吗?先谢谢了!

【问题讨论】:

    标签: streamreader readblock


    【解决方案1】:

    首先,仔细阅读 StreamReader.ReadBlock() 文档http://msdn.microsoft.com/en-us/library/system.io.streamreader.readblock.aspx 并与您正在做的事情进行比较:

    • 第二个参数(索引器)应该在您传入的块的范围内,但您传递的内容可能会在一次迭代后超过它。由于看起来您想重用内存块,因此在此处传递 0。
    • 第三个参数(计数)表示要读入内存块的字节数;传递大于块大小的东西可能不起作用(取决于实现)
    • ReadBlock() 返回实际读取的字节数,但您递增索引器,就好像它总是会准确地返回块的大小(大多数时候,它不会)

    【讨论】:

    • charsRead = reader.ReadBlock(block, 0, block.Length);成功了。如果您正在寻找特定的字符/字符集,我仍然认为 ReadLine 更适合。我将尝试使用 ReadLine。谢谢。
    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多