Not quite the answer to your question, but this method can be much simpler:
public static void WriteFileFromStream(Stream stream, string toFile) {
Please note that I also deleted the return value, since it is almost useless since there is only 1 return statement in your code
In addition, you perform length checking on a stream, but many threads do not support length checking.
As for your problem, first check if the thread has completed. If not, you read 4 bytes. Here is the problem. Suppose you have an input stream of 6 bytes. First you check if the stream is at the end. The answer is no, since there are 6 bytes left. You read 4 bytes and check again. Of course, the answer is still missing, as 2 bytes remain. Now you read 4 more bytes, but this fails, since there are only 2 bytes. (readInt32 reads the next 4 bytes).
source share