Need help understanding Stream.Read()

前端 未结 3 1139
借酒劲吻你
借酒劲吻你 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 00:51

    Read will read whatever's available (blocking until something is available) but there may not be enough data ready to fill the buffer to start with.

    Imagine downloading data over the network - there may be megabytes of data to download, but only some of it is available to start with. So you need to keep calling Read() until you've read as much as you want.

    Stream.Read will read at most the number of bytes you've asked for, but can easily read less. Admittedly for local file streams I suspect it always reads as much as you've asked for unless the file is shorter, but that's not true of streams in general, and I don't believe it's guaranteed even for local file streams.

    0 讨论(0)
  • 2020-12-12 01:04

    From MSDN:

    When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
    
    Return Value
    
    Type: System.Int32
    The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题