c# – Filestream.Read的返回值是什么意思?如何以块的形式读取数据并进行处理?

我对C#很新,所以请耐心等待.我正在读取(使用FileStream)数据(固定大小)到小数组,处理数据然后再读取,依此类推到文件末尾.

我想过用这样的东西:

            byte[] data = new byte[30];
            int numBytesToRead = (int)fStream.Length;
            int offset = 0;

            //reading
            while (numBytesToRead > 0)
            {
                fStream.Read(data, offset, 30);
                offset += 30;
                numBytesToRead -= 30;

                //do something with the data
            }

但是我检查了文档及其示例,他们表示上述读取方法的返回值为:

“Type: System.Int32
The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached.”

它们目前无法使用是什么意思,这在读取少量数据时是否真的会发生,或者这只是大量数据?如果只是为了大,大约有多大,因为我也会在其他地方阅读更大的块.如果这种情况随时可能发生,我应该如何更改代码,以便代码仍能有效执行?

谢谢你的时间和答案.

解决方法:

read方法返回返回的字节数,可能小于请求的字节数.通常,当您读取文件时,您将获得您要求的所有字节(除非您到达文件的末尾),但是,您不能指望它始终如此.

系统可能会在立即可用的数据和需要时间检索的数据之间产生差异,以便它立即返回当前可用的数据,开始在后台读取更多数据并期望您请求其余数据另一个电话中的数据. AFAIK目前没有这样做,但这是一个合理的未来情景.

您应该获得Read方法的结果并使用它来确定您获得了多少数据.您不应该在偏移位置将其读入缓冲区,然后您无法读取大于缓冲区的文件.或者,您可以声明一个数组来保存整个流,然后您将数据读入偏移的位置.

您还应该处理Read方法返回零的情况,这意味着没有更多数据要读取.这通常不会发生,直到你到达文件的末尾,但如果它会将你的代码扔进一个永恒的循环.

byte[] data = new byte[30];
int numBytesToRead = (int)fStream.Length;
int offset = 0;

//reading
while (numBytesToRead > 0) {
  int len = fStream.Read(data, 0, data.Length);
  offset += len;
  numBytesToRead -= len;
  if (len == 0 && numBytesToRead > 0) {
    // error: unexpected end of file
  }
  //do something with the data (len bytes)
}
上一篇:c# – 为什么FileStream不作为Streamwriter的参数写入文本文件?


下一篇:C#拷贝文件