Need help understanding Stream.Read()

前端 未结 3 1138
借酒劲吻你
借酒劲吻你 2020-12-12 00:15

I am a little confused as to the steps of reading a file into buffer gradually.

from the MSDN docs

public abstract int Read(
    byte[] buffer,
             


        
3条回答
  •  囚心锁ツ
    2020-12-12 01:09

    The Read method will read at least one byte, and at most the number of bytes specified.

    The method will usually return all data that is currently available. If the stream is for example coming over the internet it will usually return what it has recieved to far, and for a file stream it will usually return the entire file.

    However, it's up to the implementation to decide what the best behaviour is. It might for example first return what it can get from the file cache, which can be returned immediately, and let you do another call to get the data that requires an actual disk read.

    When using the Read method, you should always use a loop so that you are sure to get all the data. It might not seem neccesary if the first call appears to always return all data, but there might be situations where it doesn't.

提交回复
热议问题