I'm just writing an simple method witch reading data from a general stream - which means it could be possibly a FileStream or a NetworkStream without knowing the length of it. I repeatly read the stream into a byte[] and push the data to another stream or whatever. My question is, how can I notice the stream is finished? I tried to return when the Read method returns 0 - is it the right way to do so? It seems that it's ok for reading files but meet problems for reading data from network, sometimes.
Yes, calling Read repeatedly and finishing when it returns 0 is exactly the right way to do it.
Network streams are fine with this as well - they will block until any data is received or the stream is disconnected. Look at the documentation for Stream.Read:
The return value is zero only if the position is currently at the end of the stream. The implementation will block until at least one byte of data can be read, in the event that no data is available. Read returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With